简体   繁体   English

实体框架复杂类型验证(数据库优先)

[英]Entity Framework Complex Type Validation (DB First)

I'm currently using Entity framework 6 to interface between the user interface and the back end database, however I have a problem with validation on fields in a complex type. 我目前正在使用实体框架6在用户界面和后端数据库之间建立接口,但是我对复杂类型的字段进行验证存在问题。 I'm using the database first approach. 我正在使用数据库优先方法。

I created my model based on existing database, then converted fields into a complex type. 我基于现有数据库创建了模型,然后将字段转换为复杂的类型。

For example, user model. 例如,用户模型。

public partial class User {
    public User() {
        this.DeliveryAddress = new Address();
        this.InvoiceAddress = new Address();
    }

    public Address DeliveryAddress { get; set; }
    public Address InvoiceAddress { get; set; }
}

Complex type 复合型

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; }
}

I mapped the table correctly in the model browser and everything is compiling. 我在模型浏览器中正确映射了表,并且一切都在编译。 However when trying to save it throws an error that validation failed. 但是,当尝试保存它时,会抛出一个错误,提示验证失败。 After a bit of investigation it turns out for some reason all the complex type fields are required. 经过一番调查后,发现由于某些原因需要所有复杂类型字段。 Which I find strange as they are strings which can be null and even in database the fields are nullable. 我觉得很奇怪,因为它们是可以为null的字符串,即使在数据库中,这些字段也可以为null。 As a work around I created a partial class of Address with a constructor to initialize all the fields to an empty string which is a temporary work around. 解决方法是,使用构造函数创建Address的局部类,以将所有字段初始化为空字符串,这是临时解决方法。 However this isn't ideal. 但是,这不是理想的。

Code which saves the details. 保存详细信息的代码。 (Mvc Action) (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);
}

Has anyone come across a similar situation? 有人遇到过类似情况吗? Maybe Im missing something which needs to be configured. 也许我错过了一些需要配置的东西。

After much searching, I found a solution to my issue. 经过大量搜索,我找到了解决问题的方法。 In the model browser options under complex types, you can expand the complex types to reveal the fields in the complex type and in the properties of each one there is a property 'Nullable' which is set to false. 在复杂类型下的模型浏览器选项中,可以展开复杂类型以显示复杂类型中的字段,并且在每个属性中的属性中都有一个属性“ Nullable”,该属性设置为false。 I set these to true, and it now saves without issues. 我将它们设置为true,现在可以毫无问题地保存。 Im quite surprised it doesnt pick up the type and change it to allow nulls depending on the type. 我很惊讶它没有选择类型并根据类型将其更改为允许空值。

Visual Studio模型浏览器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM