我不知道這是行爲設計還是EF6中的錯誤,或者還有其他方法可以做到這一點。有了這個複雜類型:使用IsNullable = true與IsNullable = true衝突的配置設置IsNullable = false重用ComplexType
[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();
}
「添加遷移」命令失敗,並顯示以下錯誤: 爲類型屬性「名稱」指定了衝突的配置設置「本公司」: ISNULLABLE =與ISNULLABLE =真
虛假衝突,但它沒有任何意義的,因爲我定義的AcademicInfo表不能爲空,併爲空的客戶表中的字段。
HasColumnName()定義屬性將在數據庫中的目標列。您正試圖爲同一列定義不同的名稱和可空的規則。默認情況下,FK應該是可以爲空的,所以您需要使用HasOne()和WithOne()方法進行非空值 – monica
@james,它們不是同一個colums,因爲在數據庫中可定義的列在Customer表中定義並且非空值的在AcademicInfo表中。沒有參與問題FK所以我刪除與其相關的代碼: modelBuilder.Entity() \t \t \t \t .HasRequired(A => a.Customer) \t \t \t \t .WithOptional( c => c.AcademicInfo) \t \t \t \t .WillCascadeOnDelete(true); –
Lupa