Environment: Net Core 3.1 Web Api, Microsoft.AspNetCore.OData 7.4.0-beta
I've an OData api controller CustomersController that it's working fine, but $expand always returns NullReferenceException. Customer has a one to many Contacts and Addresses.
This is the code of action method:
[HttpGet]
[ODataRoute]
[EnableQuery]
public IActionResult Get()
{
try
{
var customers = _context.Customers;
_logger.LogInfo($"Returned {customers.Count()} customers from database.");
return Ok(customers);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside Get customers action: {ex.Message}");
return StatusCode(500, "Internal server error");
}
}
And this is the customer object definition:
public class Customer : BaseEntity
{
public Guid CustomerId { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(100, ErrorMessage = "Name can't be longer than 100 characters")]
public string Name { get; set; }
[StringLength(100, ErrorMessage = "Commercial name can't be longer than 100 characters")]
public string CommercialName { get; set; }
[Required(ErrorMessage = "Tax code is required")]
[StringLength(25, ErrorMessage = "Tax code can't be longer than 25 characters")]
public string TaxCode { get; set; }
[StringLength(250, ErrorMessage = "Email can't be longer than 250 characters")]
[EmailAddress]
public string Email { get; set; }
[StringLength(250, ErrorMessage = "Url can't be longer than 250 characters")]
public string Url { get; set; }
public ICollection<Contact> Contacts { get; set; }
public ICollection<Address> Addresses { get; set; }
public ICollection<Work> Works { get; set; }
}
DbContext configuration:
// Table
builder.ToTable("Customers");
builder.HasKey(b => b.CustomerId);
// Relationships
builder.HasMany(b => b.Contacts)
.WithOne(b => b.Customer)
.HasForeignKey(b => b.CustomerId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(b => b.Addresses)
.WithOne(b => b.Customer)
.HasForeignKey(b => b.CustomerId)
.OnDelete(DeleteBehavior.Cascade);
I have another controller but with one to one relationships and this controller works fine with $expand with the same code in action method.
Any idea about what is failing?
Regards
I've found that this is an issue with OData Web Api library version.
This is the issue:
Regards
Related
I have define a Entity call Users...that is mapped to Users table with EF.
public partial class Users
{
public long User_id { get; set; }
[Required]
[StringLength(30, ErrorMessage = "LastName cannot be longer than 30 characters.")]
public string LastName { get; set; }
[Required]
[StringLength(30, ErrorMessage = "Name cannot be longer than 30 characters.")]
public string Name { get; set; }
public int Country_id { get; set; }
public Nullable<int> State_id { get; set; }
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<System.DateTime> UpDateTime { get; set; }
[RegularExpression(#"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]
[Required]
[StringLength(9, MinimumLength = 3, ErrorMessage = "Password cannot be longer than 9 characters.")]
public string Password { get; set; }
public int Rol_id { get; set; }
public byte[] Picture { get; set; }
public string CodArea { get; set; }
public string PhoneNumber { get; set; }
public virtual Ages Ages { get; set; }
public virtual Countries Countries { get; set; }
[NotMapped] // Does not effect with your database
[RegularExpression(#"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]
[StringLength(9, MinimumLength = 3, ErrorMessage = "Confirm Password cannot be longer than 9 characters.")]
[Compare("Password")]
public virtual string ConfirmPassword { get; set; }
}
I use this entity to inherit from my Create View...
When I Update, I do not need a lot of this properties. I defined a a new Entity called UserEditView with this definition. I do not have Password and ConfirmPassword.
public partial class UserEditView
{
public long User_id { get; set; }
[Required]
[StringLength(30, ErrorMessage = "LastName cannot be longer than 30 characters.")]
public string LastName { get; set; }
[Required]
[StringLength(30, ErrorMessage = "Name cannot be longer than 30 characters.")]
public string Name { get; set; }
public int Country_id { get; set; }
public Nullable<int> State_id { get; set; }
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<System.DateTime> UpDateTime { get; set; }
[RegularExpression(#"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]
[Required]
[StringLength(9, MinimumLength = 3, ErrorMessage = "Password cannot be longer than 9 characters.")]
public byte[] Picture { get; set; }
public string CodArea { get; set; }
public string PhoneNumber { get; set; }
}
I defined a Mapper in my Global asax and Ignore those properties I dot not need.
cfg.CreateMap<Users, UserEditView>();
cfg.CreateMap<UserEditView, Users>()
.ForMember(x => x.CreationDate, opt => opt.Ignore())
.ForMember(x => x.Password, opt => opt.Ignore())
.ForMember(x => x.ConfirmPassword, opt => opt.Ignore())
.ForMember(x => x.Rol_id, opt => opt.Ignore());
}
When I Update, I mapp UserEditView to Users so I can call _db.SaveChanges() like this.
public async Task<ActionResult> Edit(UserEditView model, System.Web.HttpPostedFileBase image = null)
{
try
{
if (!ModelState.IsValid)
{
return View(model);
}
model.user.UpDateTime = DateTime.Now;
model.user.IP = Request.UserHostAddress;
model.user.Url = UserValidation.EncriptacionURL(model.user.Email);
var user = _db.Users.FirstOrDefault(p => p.User_id == model.user.User_id);
if (user == null)
{
return View(model);
}
Mapper.Map<UserEditView, Users>(model.user, user);
_db.Entry(user).State = System.Data.Entity.EntityState.Modified;
_db.SaveChanges();
}
}
in user I have the data I have in Users table. So ConfirmPassword is null because it is set as [NotMapped].
On _db.SaveChanges() I have an error because ConfirmPassword is null, so, when it is compared with Users Entity, it is compared whith Password property and failed.
How can I work when using [NotMapped] properties there is null?
Thanks
The problem I had in a Property ConfirmPassword I have add to my Users Entity with the Notation [NotMapped]. That case me a problem, when I do AutoMapper to Update Modified fields. Entity Validation ocurrs and ConfirmPassowrd is null, so, when validations ocurrs, I had an error on SaveChanges();.
I solved it adding
context.Configuration.ValidateOnSaveEnabled = false;
New to MVC. When I try to add a user to the database using Entity Framework Database First I get this exception:
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
This is the code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(RegisterViewModel account)
{
if (ModelState.IsValid)
{
using (db)
{
bool duplicate = db.Users.Any(a => a.UserName == account.UserName);
if (duplicate)
{
ModelState.AddModelError("", "Username already exists in database!");
}
else
{
db.Users.Add(new StoreFront.Models.User { UserName = account.UserName, Password = account.Password, EmailAddress = account.EmailAddress, IsAdmin = false, DateCreated = DateTime.Now });
db.SaveChanges();
ModelState.Clear();
ModelState.AddModelError("RegisterSuccess", "Successfully registered!");
}
}
}
return View();
}
I have validation in my RegisterViewModel for all fields, and when I debug, IsValid = true, otherwise it wouldn't run anyway. Any help would be greatly appreciated...I have been struggling with this for a while.
P.S. Yes the password is currently being stored as a string, this is just a test project that won't be used in the real world.
EDIT: Added Models:
User Model from database:
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Addresses = new HashSet<Address>();
this.Orders = new HashSet<Order>();
this.ShoppingCarts = new HashSet<ShoppingCart>();
}
public int UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public Nullable<bool> IsAdmin { get; set; }
public Nullable<System.DateTime> DateCreated { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> DateModified { get; set; }
public string ModifiedBy { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Address> Addresses { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Order> Orders { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ShoppingCart> ShoppingCarts { get; set; }
}
Partial Model to add ConfirmPassword:
namespace StoreFront.Models
{
[MetadataType(typeof(RegisterViewModel))]
public partial class User
{
[DisplayName("Confirm Password")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Passwords must match")]
public string ConfirmPassword { get; set; }
}
}
RegisterViewModel:
public class RegisterViewModel
{
public int UserID { get; set; }
[DisplayName("Username")]
[Required(ErrorMessage = "Username is required")]
public string UserName { get; set; }
[DisplayName("Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[DisplayName("Confirm Password")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Passwords must match")]
public string ConfirmPassword { get; set; }
[DisplayName("Email")]
[Required(ErrorMessage = "Email is required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$",
ErrorMessage = "Please enter a valid email")]
public string EmailAddress { get; set; }
public Nullable<bool> IsAdmin { get; set; }
public Nullable<System.DateTime> DateCreated { get; set; }
}
Fix: When I looked up a tutorial about MVC it asked em to create a partial class and a meta class. That was for code first I believe, which basically made it a new field that my database didn't have a spot for, and I am using database first. So I removed the deleted the partial class for User and it stopped making ConfirmPassword an actual field in the database.
Don't know the real works of it, or if what I said makes sense, but I hope this helps someone eventually.
Remove
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$",
ErrorMessage = "Please enter a valid email")]
from RegisterViewModel
In the Checkout Controller I have the code
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
var order = new Order();
TryValidateModel(order);
....
The model looks like this
[Bind(Exclude="OrderId")]
public partial class Order
{
[ScaffoldColumn(false)]
public int OrderId { get; set; }
[ScaffoldColumn(false)]
public string Username { get; set; }
[Required(ErrorMessage= "First Name is required")]
[DisplayName("First Name")]
[StringLength(160)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required")]
[DisplayName("Last Name")]
[StringLength(160)]
public string LastName { get; set; }
[Required(ErrorMessage="Address is required")]
[StringLength(70)]
public string Address { get; set; }
[Required(ErrorMessage = "City is required")]
[StringLength(40)]
public string City { get; set; }
[Required(ErrorMessage = "State is required")]
[StringLength(40)]
public string State { get; set; }
[Required(ErrorMessage = "Postal Code is required")]
[DisplayName("Postal Code")]
[StringLength(10)]
public string PostalCode { get; set; }
[Required(ErrorMessage="Country is required")]
[StringLength(40)]
public string Country { get; set; }
[Required(ErrorMessage= "Phone is required")]
[StringLength(24)]
public string Phone { get; set; }
[Required(ErrorMessage="Email Address is required")]
[DisplayName("Email Address")]
[RegularExpression(#"[A-za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage="Email is not valid.")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[ScaffoldColumn(false)]
public decimal Total { get; set; }
[ScaffoldColumn(false)]
public DateTime OrderDate { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
}
I can stop right before the TryValidateModel line and look at form values like
? Request.Form["FirstName"]
"Michael"
? values["FirstName"]
"Michael"
So why does TryValidateModel(order); return false and the order object does not get populated?
Update
To clarify my question I know false means it can not bind but I do not know why it can not bind. Or that it should through the TryValidateModel(or even the ValidateModel)
But what is interesting is that if I change my method signature to
public ActionResult AddressAndPayment(Order order)
order gets populated correctly. So if it is able to bind in the Method call why not TryValidateModel(or even the ValidateModel)?
I am using MVC 4
TryValidateModel returns false when validation of the Form Model against your Orders Model Fails, thus Binding fails.
I hate using
TryValidateModel(order);
and prefer
ValidateModel(order);
early on while developing my page, because binding is a delicate process. This way, if the model fails to bind, I get an exception and an indicative error msg.
I have this data model:
public class User
{
public long UserID { get; set; }
[Required(ErrorMessage = "User name is required.")]
[MaxLength(50, ErrorMessage = "User name cannot be longer than 50 characters.")]
public string UserName { get; set; }
[Email]
[Required(ErrorMessage = "Email is required.")]
[MaxLength(100, ErrorMessage = "Email cannot be longer than 100 characters.")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required.")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
[MaxLength(150, ErrorMessage = "Full name cannot be longer than 150 characters.")]
public string FullName { get; set; }
public int UserTypeID { get; set; }
public virtual UserType UserType { get; set; }
public virtual ICollection<Page> Pages { get; set; }
}
and I'm using this model to only edit some fields (password shouldn't be editable):
public class EditUserModel
{
public long UserID { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Email]
[Required(ErrorMessage = "Email is required.")]
[MaxLength(100, ErrorMessage = "Email cannot be longer than 100 characters.")]
public string Email { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Full name")]
[MaxLength(150, ErrorMessage = "Full name cannot be longer than 150 characters.")]
public string FullName { get; set; }
public int UserTypeID { get; set; }
public virtual UserType UserType { get; set; }
}
but I'm confused on how to pass the EditUserModel to my data context to update it. Sorry if seems elementary, but I'm really stumped.
This is the auto-generated edit action that I modified:
[IsAdministrator]
[HttpPost]
public ActionResult Edit(EditUserModel user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeId", "Name", user.UserTypeID);
return View(user);
}
This is the line I'm having trouble with:
db.Entry(user).State = EntityState.Modified;
The reason I created a custom class was to avoid exposing the password from the view.
This can't work because you're trying to save view model.
You could use AutoMapper to rewrite data from view model to your data model. After that you should be able to save changes.
User userModel = Mapper.Map<EditUserModel, User>(user);
userModel = // todo: get password from database
// todo: attach your model to context and save changes
I'm using Entity Framework Code First and that approach works great.
Hi I have an Invoice type like:
public class Invoice : IEntity, IValidatableObject
{
public virtual int Id { get; set; }
[Required(ErrorMessage = "Invoice Number is a required field.")]
[Display(Name = "Invoice Number:")]
public virtual string InvoiceNumber { get; set; }
[Required(ErrorMessage = "Invoice Date is a required field.")]
[Display(Name = "Invoice Date:")]
[DataType(DataType.Date)]
public DateTime? InvoiceDate { get; set; }
[Required(ErrorMessage = "Organisation is a required field.")]
[Display(Name = "Organisation:")]
public int OrganisationId { get; set; }
[Required(ErrorMessage = "Region is a required field.")]
[Display(Name = "Region:")]
public virtual int? AreaId { get; set; }
[Required(ErrorMessage = "Total (Exc. GST) is a required field.")]
[Display(Name = "Total (Exc. GST):")]
public decimal? TotalExcludingGst { get; set; }
[Required(ErrorMessage = "Total (Inc. GST) is a required field.")]
[Display(Name = "Total (Inc. GST):")]
public decimal? TotalIncludingGst { get; set; }
public virtual string CreatedByUserName { get; set; }
public virtual DateTime CreatedDateTime { get; set; }
public virtual string LastModifiedByUserName { get; set; }
public virtual DateTime? LastModifiedDateTime { get; set; }
// Navigation properties
public virtual Area Area { get; set; }
public virtual Organisation Organisation { get; set; }
public virtual ICollection<InvoiceLine> InvoiceLines { get; set; }
#region IValidatableObject Members
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((TotalExcludingGst + (TotalExcludingGst * .15m)) != TotalIncludingGst) {
yield return new ValidationResult("The total (exc. Gst) + Gst does not equal the total (inc. Gst).");
}
}
#endregion
What I want to do is make sure on insert update that the combination of Organsation and InvoiceNumber is unique.
I'm considering something like:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var repository = new Repository<Invoice>();
if(!repositoy.CheckUnique(Id)) {
yield return new ValidationResult("The combination of Organisation and Invoice number is already in use");
}
}
Is this bad practise? To be instantiating the repository inside the model?
Is there a better way?
Your solution is not work correctly in a multi user scenario. Because between checking whether an ID exists and saving changes another record maybe inserted with that same ID.
You can create a Unique Constraint on your table. This is the safe way to ensure duplicates are not created.
Current versions of EF does not model/support Unique Constraints. However what you can do is catch the specific exception and check the error message. Then show the errors
try
{
//updation logic
context.SaveChanges();
}
catch (System.Data.DataException de)
{
Exception innerException = de;
while (innerException.InnerException != null)
{
innerException = innerException.InnerException;
}
if (innerException.Message.Contains("Unique_constraint_name"))
{
ModelState.AddModelError(string.Empty, "Error Message");
return;
}
ModelState.AddModelError(string.Empty, "Error Message");
return View();
}
If you are using ASP.NET Web forms you can check this answer