I am having the following issue when trying to make a post request to my orders controller. I am informed that certain fields are required, even though I have filled them in. Can anyone correct me on where I am going wrong here?
Here is my controller method:
public class OrdersController : ApiControllerBase
{
[HttpGet]
public async Task<ActionResult<OrdersViewModel>> GetOrderAsync()
{
return await Mediator.Send(new GetOrdersQuery());
}
[HttpPost]
[Produces("application/json")]
public async Task<ActionResult<bool>> Create(CreateOrderCommand command)
{
return await Mediator.Send(command);
}
}
Here is the CreateOrderCommand and its Handler:
[DataContract]
public class CreateOrderCommand : IRequest<bool>
{
[DataMember]
public string UserId { get; private set; }
[DataMember]
public string UserName { get; private set; }
[DataMember]
public string Street { get; private set; }
[DataMember]
public string City { get; private set; }
[DataMember]
public string Country { get; private set; }
[DataMember]
public string PostCode { get; private set; }
[DataMember]
public string CardNumber { get; private set; }
[DataMember]
public string CardHolderName { get; private set; }
[DataMember]
public DateTime ExpiryDate { get; private set; }
[DataMember]
public string CardSecurityNumber { get; private set; }
[DataMember]
public CardTypeEnum CardType { get; private set; }
[DataMember]
private readonly List<OrderItemDTO> _orderItems;
[DataMember]
public IEnumerable<OrderItemDTO> OrderItems => _orderItems;
public CreateOrderCommand()
{
_orderItems = new List<OrderItemDTO>();
}
public CreateOrderCommand(List<OrderItemDTO> orderItems, string userId, string userName, string city, string street, string country, string postcode,
string cardNumber, string cardHolderName, DateTime expiryDate, string cardSecurityNumber, CardTypeEnum cardType) : this()
{
_orderItems = orderItems;
UserId = userId;
UserName = userName;
City = city;
Street = street;
Country = country;
PostCode = postcode;
CardNumber = cardNumber;
CardHolderName = cardHolderName;
ExpiryDate = expiryDate;
CardSecurityNumber = cardSecurityNumber;
CardType = cardType;
}
}
public record OrderItemDTO
{
public decimal BookPrice { get; init; }
public string BookTitle { get; init; }
public int Quantity { get; init; }
public int BookCatalogueId { get; init; }
public string BookImageUrl { get; init; }
}
public class CreateOrderCommandHandler : IRequestHandler<CreateOrderCommand, bool>
{
private readonly IOrderRepository _orderRepository;
private readonly ILogger<CreateOrderCommandHandler> _logger;
public CreateOrderCommandHandler(IOrderRepository orderRepository, ILogger<CreateOrderCommandHandler> logger)
{
_orderRepository = orderRepository;
_logger = logger;
}
public async Task<bool> Handle(CreateOrderCommand command, CancellationToken cancellationToken)
{
var deliveryAddress = new DeliveryAddress(command.Street, command.City, command.Country, command.PostCode);
var userId = (!string.IsNullOrEmpty(command.UserId)) ? command.UserId : "1";
var userName = (!string.IsNullOrEmpty(command.UserName)) ? command.UserName : "Christopher";
var order = new Order(userId, userName, deliveryAddress, command.CardType, command.CardNumber, command.CardSecurityNumber, command.CardHolderName, command.ExpiryDate);
if (order == null)
throw new NotFoundException();
foreach (var item in command.OrderItems)
{
order.AddOrderItem(item.BookCatalogueId, item.BookTitle, item.BookPrice, item.BookImageUrl, item.Quantity);
}
_logger.LogInformation("----- Creating Order - Order: {#Order}", order);
_orderRepository.Add(order);
return await _orderRepository.UnitOfWork
.SaveEntitiesAsync(cancellationToken);
}
}
}
Here is how I have registered my services:
public static IServiceCollection AddApplicationServices(this IServiceCollection services)
{
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
services.AddMediatR(Assembly.GetExecutingAssembly());
return services;
}
Here is my problem when I try to post a request to my controller:
If you use the private setter, you cannot get the value. Change your model like below:
[DataContract]
public class CreateOrderCommand : IRequest<bool>
{
[DataMember]
public string UserId { get; set; } //remove all the private accessor...
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Street { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string PostCode { get; set; }
[DataMember]
public string CardNumber { get; set; }
[DataMember]
public string CardHolderName { get; set; }
[DataMember]
public DateTime ExpiryDate { get; set; }
[DataMember]
public string CardSecurityNumber { get; set; }
[DataMember]
public CardTypeEnum CardType { get; set; }
[DataMember]
private List<OrderItemDTO> _orderItems; //remove readonly
[DataMember]
public List<OrderItemDTO> OrderItems //change here..
{
get { return _orderItems; }
set { _orderItems = value; }
}
public CreateOrderCommand()
{
_orderItems = new List<OrderItemDTO>();
}
public CreateOrderCommand(List<OrderItemDTO> orderItems, string userId, string userName, string city, string street, string country, string postcode,
string cardNumber, string cardHolderName, DateTime expiryDate, string cardSecurityNumber,CardTypeEnum cardType) : this()
{
_orderItems = orderItems;
UserId = userId;
UserName = userName;
City = city;
Street = street;
Country = country;
PostCode = postcode;
CardNumber = cardNumber;
CardHolderName = cardHolderName;
ExpiryDate = expiryDate;
CardSecurityNumber = cardSecurityNumber;
CardType = cardType;
}
}
Related
I'm having a hard time passing the value of an object to a model.
I wanted to pass the data from this obj to the model class
SingleTransactResponse obj = JsonConvert.DeserializeObject<SingleTransactResponse>(await response.Content.ReadAsStringAsync());
SaveTransaction(JsonConvert.SerializeObject(obj));
I used this function to get the data from the model and save it to the database
PayoutEntities payoutdb = new PayoutEntities();
public String SaveTransaction(payout_transaction model)
{
payoutdb.payout_transaction.Add(model);
payoutdb.SaveChanges();
return "Success";
}
SingleTransactResponse Class
public class SingleTransactResponse {
public String senderRefId { get; set; }
public String tranRequestDate { get; set; }
public String particulars { get; set; }
public List<Beneficiary> beneficiary { get; set; }
}
Beneficiary Class
public class Beneficiary
{
public String accountNumber { get; set; }
public String name { get; set; }
public List<Address> address { get; set; }
}
Address Class
public class Address
{
public String line1 { get; set; }
public String line2 { get; set; }
public String city { get; set; }
public String province { get; set; }
public String zipCode { get; set; }
public String country { get; set; }
}
payout_transaction class
public partial class payout_transaction
{
public string transid { get; set; }
public string batchid { get; set; }
public string senderRefId { get; set; }
public string requestDate { get; set; }
public string benefName { get; set; }
public string benefacctno { get; set; }
public string status { get; set; }
public string errdesc { get; set; }
public string transaction_fee { get; set; }
}
I'm just having a hard time converting the obj to the model. I've tried JsonConvert.SerializeObject(obj) but it only converts it to string. Is there any possible way to do this or any work around to solve this problem?
you can do like this
var payoutModel = new payout_transaction
{
senderRefId = obj.senderRefId,
requestDate = obj.tranRequestDate,
.... other properties
}
SaveTransaction(payoutModel);
I am using code-first Entity Framework in my ASP.NET MVC project
I have these tables
User
public class User:IBaseEntity
{
public User()
{
UserRoles = new List<UserRole>();
}
public int ID { get; set; }
public int RoleId { get; set; }
public string Email { set; get; }
public string Password { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public string Company { set; get; }
public string Address1 { set; get; }
public string Address2 { set; get; }
public string City { set; get; }
public string PostalCode { set; get; }
public string Country { set; get; }
public string State { set; get; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
Role
public class Role : IBaseEntity
{
public int ID { get; set; }
public string RoleName { get; set; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
}
UserRole
public class UserRole : IBaseEntity
{
public int ID { get; set; }
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
IBaseEntity
public interface IBaseEntity
{
int ID { get; set; }
}
I need seed data User with UserRole
How can I put UserRole in method create User?
public void CreateRoles(CMSDbContext context)
{
if (context.Roles.Count() == 0)
{
List< Role> listRole = new List<Role>()
{
new Role()
{
RoleName = "Admin",
Active = true,
CreatedOn = DateTime.Now
},
new Role()
{
RoleName = "User",
Active = true,
CreatedOn = DateTime.Now
}
};
context.Roles.AddRange(listRole);
context.SaveChanges();
}
}
public void CreateUser(CMSDbContext context)
{
if (context.Users.Count() == 0)
{
List<User> listUser = new List<User>()
{
new User()
{
FirstName = "David",
LastName = "Lima",
Active = true,
Email = "admin#domain.com",
Address1 = "New York",
Address2 = "Chicago",
Company = "Test",
CreatedOn = DateTime.Now,
PostalCode = "123456",
State = "Test",
City = "test",
UserRoles =???
Password = CMS.Common.HashMD5.CreateMD5("12356")
}
};
context.Users.AddRange(listUser);
context.SaveChanges();
}
}
}
Please focus on method CreateUser have property UserRole, not sure what I can put here. I also create some roles in Role table (admin, user)
I am getting stuck at this point.
Any help will be appreciated
Thanks all
I'm using the NBuilder library to build mock http responses, everything works fine in Android, but in iOS each time that I want to build a model class this exception is fired.
"FizzWare.NBuilder.TypeCreationException" and It says that my X model class doesn't have a parametless constructor, which actually has!. For example this model class:
public class Actor
{
public Actor() {
}
[JsonProperty("authorities")]
public List<Authority> Authorities { get; set; }
[JsonProperty("imageDerivatives")]
public ImageDerivatives ImageDerivatives { get; set; }
[JsonProperty("profileFileId")]
public PictureFile ProfilePicture { get; set; }
[JsonProperty("role")]
public Role Role { get; set; }
[JsonProperty("roleId")]
public int RoleId { get; set; }
[JsonProperty("status")]
public bool Status { get; set; }
[JsonProperty("updatedAt")]
public DateTime UpdatedAt { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("createdAt")]
public DateTime CreatedAt { get; set; }
[JsonProperty("departmentId")]
public int DepartmentId { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("isAppAdmin")]
public bool IsAppAdmin { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
And this is how I build the mock response:
private Actor GetRandomActor()
{
return Builder<Actor>.CreateNew()
.With(a => a.FirstName = GetRandomFirstName())
.With(a => a.LastName = GetRandomLastName())
.With(a => a.ProfilePicture = GetRandomPictureFile())
.With(a => a.Email = GetRandomEmail())
.With(a => a.Username = GetRandomUserName())
.Build();
}
Try adding the Preserve attribute to your constructor so it does not get removed by the Linker:
[Preserve]
public Actor() {}
(Or add it at the class level [Preserve (AllMembers = true)])
I have three simple classes and I am wiring up EF6 to an existing database.
Classes are as follows
namespace Infrastructure.Models
{
[Table("Applications")]
public class Application
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ApplicationID { get; set; }
public DateTime DateTime { get; set; }
public string CompletedZipFileURL { get; set; }
public virtual BusinessInfo BusinessInfo { get; set; }
public Application()
{
this.ApplicationID = Guid.NewGuid();
this.DateTime = DateTime.Now;
this.CompletedZipFileURL = string.Empty;
this.BusinessInfo = new BusinessInfo();
this.BusinessInfo.ApplicationID = this.ApplicationID;
}
}
[Table("BusinessInfo")]
public class BusinessInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid BusinessID { get; set; }
public Guid ApplicationID { get; set; }
public string BusinessName { get; set; }
public string BusinessType { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string BusinessTelephone { get; set; }
public string FEIN { get; set; }
public string ILSalesTaxNo { get; set; }
public string IncorporateDate { get; set; }
public virtual ApplicantInfo ApplicantInfo {get;set;}
public BusinessInfo()
{
this.BusinessID = Guid.NewGuid();
this.ApplicantInfo = new ApplicantInfo();
this.ApplicantInfo.BusinessID = this.BusinessID;
}
}
public class ApplicantInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ApplicantID { get; set; }
public Guid BusinessID { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string HomeAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string EmailAddress { get; set; }
public string PhoneNo { get; set; }
public string Criminal { get; set; }
public ApplicantInfo()
{
this.ApplicantID = Guid.NewGuid();
}
}
}
My Context Class looks like the following:
public class SIDEntities : DbContext
{
public SIDEntities() : base(Settings.GetSetting("ConnectionString"))
{
base.Configuration.ProxyCreationEnabled = false;
base.Configuration.LazyLoadingEnabled = false;
}
public virtual DbSet<Infrastructure.Models.Application> Application { get; set; }
public virtual DbSet<Infrastructure.Models.BusinessInfo> BusinessInfo { get; set; }
public virtual DbSet<Infrastructure.Models.ApplicantInfo> ApplicantInfo { get; set; }
}
On my existing database, I have the following table names and fields:
Applications (ApplicationID : uniqueidentifier, DateTime : datetime, CompletedZipFileURL : varchar(500))
BusinessInfo (BusinessID : uniqueidentifier, ApplicationID : uniqueidentifier,...)
ApplicationInfo (ApplicantID : uniqueidentifier, BusinessID : uniqueidentifier, ...)
For some reason, as soon as I attempt to do a query against the root Application POCO, I am receiving an error to the effect of "{"Invalid column name 'BusinessInfo_BusinessID'."}".
I have attempted to debug this issue checking out various SO posts but the examples/fixes don't apply to my database first scenario.
The query that is throwing the exception is:
public static Infrastructure.Models.Application Find(Guid id)
{
using (SIDEntities cntx = new SIDEntities())
{
Infrastructure.Models.Application x = new Infrastructure.Models.Application();
//the line below is where the error occurs
x = cntx.Application.Where(m => m.ApplicationID == id).SingleOrDefault();
return x;
}
}
I can see while debugging that the query being generated from LINQ is as follows
SELECT 1 AS [C1],
[Extent1].[ApplicationID] AS [ApplicationID],
[Extent1].[DateTime] AS [DateTime],
[Extent1].[CompletedZipFileURL] AS [CompletedZipFileURL],
[Extent1].[BusinessInfo_BusinessID] AS [BusinessInfo_BusinessID]
FROM [dbo].[Applications] AS [Extent1]
I understand WHY I am getting the error back and that is because there is no "BusinessInfo_BusinessID" column in the Applications table.
I would greatly appreciate any help/pointers that I could get on this one.
Check this out
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid BusinessID { get; set; }
In your query, change Where and SingleOrDefault to:
x = cntx.Application.SingleOrDefault(m => m.ApplicationID == id);
Hope it helps
I have discovered that because I had a one-to-one relationship (that doesn't technically exist on the SQL server, I had to add a foreign key annotation underneath the [Key] property as noted:
Entity Framework 6: one-to-one relationship with inheritance
and
http://www.entityframeworktutorial.net/entity-relationships.aspx
I am getting null value for the model on postback.I am not able to find out where I am going wrong.I have seen similar questions but couldn't find any solution yet.
Here is my code:
Controller:
public ActionResult ContactUpdate(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string[] testsplit = id.Split(',');
List<int> intTest = new List<int>();
foreach (string s in testsplit)
intTest.Add(int.Parse(s));
ObjectParameter ObjParam = new ObjectParameter("ErrorCode", 0);
var cont = db.spErrorContactGet(365, ObjParam);
var ToBeUpdated = (from contacts in cont
where intTest.Contains(contacts.ResponseID)
select contacts);
IEnumerable<spErrorContactGet_Result> Update = ToBeUpdated.ToList();
return View(Update);
}
[HttpPost]
public ActionResult ContactUpdate(List<spErrorContactGet_Result> Res)
{
if (Res == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do something
// redirect to another view
}
Here is the model class:
public class spErrorContactGet_Result
{
public int ResponseID { get; set; }
public string ContactAlchemyMessage { get; set; }
public string ContactTeamAlchemyMessage { get; set; }
public string ContactElectronicAddressAlchemyMessage { get; set; }
public string ContactAccountAlchemyMessage { get; set; }
public string CRMContactID { get; set; }
public string InfluenceLevel { get; set; }
public string JobRole { get; set; }
public string Department { get; set; }
public string DepartmentName { get; set; }
public string MobilePhone { get; set; }
public string Email { get; set; }
public string Suffix { get; set; }
public string FaxNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string JobTitle { get; set; }
public string HonorablePrefix { get; set; }
public string Prefix { get; set; }
public string ContactAuthPhoneId { get; set; }
public string ContactAuthDmailId { get; set; }
public string ContactAuthEmailId { get; set; }
public string AllowFax { get; set; }
public string PartnerContactAuthPhoneID { get; set; }
public string PartnerContactAuthDmailID { get; set; }
public string PartnerContactAuthEmailID { get; set; }
public string PrivacyStatementReviewed { get; set; }
public string PreferredLanguage { get; set; }
public string IndWorkPhone { get; set; }
public string FullNamePronunciation { get; set; }
public string CRMOwner { get; set; }
public string KeyContact { get; set; }
public string MarketingAudience { get; set; }
public bool IsSelected { get; set; }
}
}
I am unable to post the view in the right format.
It is likely that structure of your view differs from one that is of your model, they must syntactically match. If you would post your view it could help. BTW there is no 'Postback' in MVC