可选实体框架复杂类型的必需属性 [英] Required Properties on optional Entity Framework Complex Types
问题描述
我想在实体框架的复杂类型中定义 [必需]
属性。例如,我有一个 Customer
实体和一个可选的 Address
。地址实体具有必需的 PostCode
属性。
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;}
}
我不想将我的Complex类型存储为单独的实体(我实际上并没有使用Address,这只是问题的简单说明)。我不能将Customer.Address保留为空,因为这样会产生错误:
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'.
如果我提供了一个空的Address实体,则由于Required属性而使PostCode字段的验证失败。
If I supply an empty Address entity, the validation fails on the PostCode field because of the Required attribute.
有什么方法可以实现?我正在使用EF5 / NET4.5。
Is there any way to achieve this? I'm using EF5/NET4.5.
推荐答案
使用复杂类型是不可能的。如果希望它可以为空,则需要创建一个地址实体。
It's not possible with a complex type. You'll need to create an Address entity if you want it to be nullable.
EF对复杂类型所做的操作是将属性映射到同一张表-
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:
带有非-nullable列的Address_PostCode,因为它在数据库中无效,因此没有对象没有地址和邮政编码的情况下,EF无法创建行。
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.
这篇关于可选实体框架复杂类型的必需属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!