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.
Complex types are non-scalar properties of entity types that enable scalar properties to be organized within entities. Like entities, complex types consist of scalar properties or other complex type properties.
An Entity can include two types of properties: Scalar Properties and Navigation Properties. Scalar Property: The type of primitive property is called scalar properties. Each scalar property maps to a column in the database table which stores the real data.
The entity type 'ProductStockRequirements' is an optional dependent using table sharing without any required non shared property that could be used to identify whether the entity exists. If all nullable properties contain a null value in database then an object instance won't be created in the query.
Property Mapping. The Property method is used to configure attributes for each property belonging to an entity or complex type. The Property method is used to obtain a configuration object for a given property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With