Required Properties on optional Entity Framework C

2019-02-21 16:32发布

问题:

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.