我不知道这种行为是设计使然还是 EF6 中的错误,或者有另一种方法可以做到这一点。具有这种复杂类型:
[ComplexType]
public partial class Company
public bool HasValue { get { return !string.IsNullOrEmpty(this.Name); } }
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(20)]
public string PhoneNumber { get; set; }
[MaxLength(128)]
public string EmailAddress { get; set; }
}
我在这两个实体中重用它:
public partial class Customer
{
public Customer ()
{
this.Company = new Company();
}
[Key]
public int IdCustomer { get; set; }
[MaxLength(100)]
[Required]
public string FirstName { get; set; }
[MaxLength(100)]
[Required]
public string LastName { get; set; }
public Company Company { get; set; }
public virtual AcademicInfo AcademicInfo { get; set; }
}
public partial class AcademicInfo
{
public AcademicInfo()
{
this.Organization = new Company();
}
[Key, ForeignKey("Customer")]
public int IdCustomer { get; set; }
public Company Organization { get; set; }
[MaxLength(100)]
public string Subject { get; set; }
[MaxLength(100)]
public string Degree { get; set; }
public virtual Customer Customer { get; set; }
}
在 dbcontext 的 OnModelCreating 中(编辑:为了简单起见,我添加了之前省略的 FK 代码):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// ... Other code here related to entities not related to the problem reported omitted to avoid confusion.
modelBuilder.Entity<AcademicInfo>()
.HasRequired(a => a.Customer)
.WithOptional(c => c.AcademicInfo)
.WillCascadeOnDelete(true);
modelBuilder.Entity<Customer>()
.Property(p => p.Company.Name)
.HasColumnName("CompanyName")
.IsOptional(); // CONFLICT HERE
modelBuilder.Entity<Customer>()
.Property(p => p.Company.EmailAddress)
.HasColumnName("CompanyEmailAddress")
.IsOptional(); //CONFLICT HERE
modelBuilder.Entity<Customer>()
.Property(p => p.Company.PhoneNumber)
.HasColumnName("CompanyPhoneNumber")
.IsOptional();
modelBuilder.Entity<AcademicInfo>()
.Property(a => a.Organization.Name)
.HasColumnName("OrganizationName")
.IsRequired(); // CONFLICT
modelBuilder.Entity<AcademicInfo>()
.Property(a => a.Organization.EmailAddress)
.HasColumnName("OrganizationEmail")
.IsRequired(); // CONFLICT
modelBuilder.Entity<AcademicInfo>()
.Property(a => a.Organization.PhoneNumber)
.HasColumnName("OrganizationPhone")
.IsOptional();
}
Add-Migration 命令失败并显示以下错误:
为“公司”类型的属性“名称”指定了冲突的配置设置:
IsNullable = False 与 IsNullable = True 冲突
但这没有意义,因为我定义了 AcademicInfo 表中不可为 null 和 Customer 表中为 null 的字段。
最佳答案
这是一个老问题,但对 EF 6.1.3 版仍然有效。
根据 this issue,行为是关于如何配置特定复杂类型的 Entity Framework 限制。
关于c# - 与 IsNullable = true IsNullable = false 重用 ComplexType 的配置设置冲突,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40646017/