我目前正在使用Entity框架6来连接用户界面和后端数据库,但是我对复杂类型的字段进行验证时遇到问题。我正在使用数据库第一种方法。
我基于现有数据库创建了我的模型,然后将字段转换为复杂类型。
例如,用户模型。
public partial class User {
public User() {
this.DeliveryAddress = new Address();
this.InvoiceAddress = new Address();
}
public Address DeliveryAddress { get; set; }
public Address InvoiceAddress { get; set; }
}
复杂类型
public partial class Address {
public string Address1 { get; set; }
public string Address2 { get; set; }
public string CompanyName { get; set; }
public string Country { get; set; }
public string County { get; set; }
public string Firstname { get; set; }
public string Postcode { get; set; }
public string Surname { get; set; }
public string TownCity { get; set; }
}
我在模型浏览器中正确映射了表,所有内容都在编译中。但是,在尝试保存时会抛出验证失败的错误。经过一些调查后,由于某种原因,所有复杂类型字段都是必需的。我觉得很奇怪,因为它们是可以为null的字符串,即使在数据库中,字段也可以为空。作为解决方法,我使用构造函数创建了一个局部类Address,将所有字段初始化为空字符串,这是一个临时解决方法。然而,这并不理想。
保存详细信息的代码。 (Mvc行动)
public ActionResult UpdateDetails(UserDetailsViewModel info) {
try {
if (ModelState.IsValid) {
var user = db.Users.Find(info.UserID);
if (user != null) {
user.DeliveryAddress = new Data.Address {
CompanyName = info.DeliveryCompanyName,
Address1 = info.DeliveryAddress1,
Address2 = info.DeliveryAddress2,
Firstname = info.DeliveryFirstname,
Postcode = info.DeliveryPostcode,
Surname = info.DeliverySurname,
TownCity = info.DeliveryCity,
};
user.InvoiceAddress = new Data.Address();
if (!info.IsInvoiceAddress) {
user.InvoiceAddress = new Data.Address {
Address1 = info.InvoiceAddress1,
Address2 = info.InvoiceAddress2,
Firstname = info.InvoiceFirstname,
Postcode = info.InvoicePostcode,
Surname = info.InvoiceSurname,
TownCity = info.InvoiceCity,
CompanyName = info.InvoiceCompanyName
};
}
db.SaveChanges();
}
return Json(new { Msg = "Ok" });
}
} catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) {
foreach (var valErs in dbEx.EntityValidationErrors) {
foreach (var valEr in valErs.ValidationErrors) {
System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", valEr.PropertyName, valEr.ErrorMessage);
}
}
return Json(new { Msg = "Err" });
} catch {
return Json(new { Msg = "Err" });
}
return PartialView("UserDetailsForm", info);
}
有没有人遇到类似的情况?也许我错过了一些需要配置的东西。