Required Properties on optional Entity Framework Complex Types

自作多情 提交于 2019-12-01 14:31:21

问题


I want to define [Required] attributes on a Complex Type in Entity Framework. For example, I have a Customer entity with an optional Address. The Address entity has a required PostCode property.

[ComplexType]
public class Address {
    public string Address1 { get; set; }
    [Required]
    public string PostCode { get; set; }
}

public class Customer {
    public int CustomerId {get;set;}
    public Address Address {get;set;}
}

I do NOT want to store my Complex type as a separate entity (I'm not actually using Address, this just an easy illustration of the problem). I cannot leave Customer.Address null, because this gives the error:

Null value for non-nullable member. Member: 'Address'.

If I supply an empty Address entity, the validation fails on the PostCode field because of the Required attribute.

Is there any way to achieve this? I'm using EF5/NET4.5.


回答1:


It's not possible with a complex type. You'll need to create an Address entity if you want it to be nullable.

What EF will do with a complex type is map the properties to the same table - which it sounds like you've intended.

Because of that - your schema for your example would look like this:

With a non-nullable column for Address_PostCode, since it's not valid in the database there's not a way for EF to create the row, without your object having an address, and a postcode.



来源:https://stackoverflow.com/questions/12856202/required-properties-on-optional-entity-framework-complex-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!