我不知道这种行为是设计的还是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 =与IsNullable = True
的错误冲突但是没有任何意义,因为我在AcademicInfo表中定义了不可为空的字段,在Customer表中定义了可空的字段。
答案 0 :(得分:0)
这是一个老问题,但仍然适用于EF版本6.1.3。
根据this issue,行为是关于如何配置特定复杂类型的实体框架限制。
这是EF的限制,某些属性方面需要存储在C-Space中,而EF没有办法配置复杂类型的特定用法。因此,您只能指定不同的S-Space方面,如ColumnName或ColumnType