2012-10-04 35 views
0

我試圖明確定義多對多關係。明確地說,我的意思是我定義了中間實體並使用Fluent API進行配置。下面是我的代碼:使用實體框架中的已定義中間實體映射多對多關係5

public class ContentType 
{ 
    public Int64 Id { get; set; } 
    public Guid SID { get; set; } 
    public String Name { get; set; } 
    public ContentType Parent { get; set; } 
    public Nullable<Int64> ParentId { get; set; } 
    public Category Category { get; set; } 
    public Nullable<Int64> CategoryId { get; set; } 
    public Boolean IsLocked { get; set; } 
    public virtual ICollection<ContentTypeColumn> ContentTypeColumns { get; set; } 
} 

public class Column 
{ 
    public Int64 Id { get; set; } 
    public Guid SID { get; set; } 
    public String SchemaName { get; set; } 
    public DataType DataType { get; set; } 
    public Int32 DataTypeId { get; set; } 
    public virtual ICollection<ContentTypeColumn> ContentTypeColumns { get; set; } 
} 

public class ContentTypeColumn 
{ 
    public Int64 Id { get; set; } 
    public Int64 ColumnId { get; set; } 
    public Column Column { get; set; } 
    public ContentType ContentType { get; set; } 
    public Int64 ContentTypeId { get; set; } 
    public Boolean IsRequired { get; set; } 
    public Boolean IsCalculated { get; set; } 
    public String Title { get; set; } 
    public Boolean IsSystem { get; set; } 
    public Expression Expression { get; set; } 
    public Int32 ExpressionId { get; set; } 
    public virtual ICollection<ColumnRule> Rules { get; set; } 
} 

public class ContentTypeConfiguration : EntityTypeConfiguration<ContentType> 
{ 
    public ContentTypeConfiguration() 
    { 
     this.ToTable("ContentType"); 
     this.Property(x => x.Id).HasColumnName("ContentTypeId").IsRequired(); 

     this.Property(x => x.Name).HasMaxLength(30); 
     this.HasOptional(x => x.Parent) 
      .WithMany() 
      .HasForeignKey(x => x.ParentId); 

     this.Property(x => x.SID).IsRequired(); 
    } 
} 

public class ContentTypeColumnConfiguration : EntityTypeConfiguration<ContentTypeColumn> 
{ 
    public ContentTypeColumnConfiguration() 
    { 
     this.ToTable("ContentTypeColumn"); 
     this.HasRequired(x => x.ContentType) 
      .WithMany() 
      .HasForeignKey(x => x.ContentTypeId); 
     this.Property(x => x.Title).HasMaxLength(50).IsRequired(); 
     this.Property(x => x.Id).HasColumnName("ContentTypeColumnId"); 
    } 
} 

出於某種原因,正在對所得ContentTypeColumn表中創建兩個外鍵。一個是可空的外鍵,另一個是不可空的。我只想要生成後者,並且我不知道可空鍵是從哪裏來的。

有什麼想法?

回答

1

這是錯誤的:

this.HasRequired(x => x.ContentType) 
    .WithMany() 
    .HasForeignKey(x => x.ContentTypeId); 

有反向導航屬性,所以你必須在WithMany使用int或EF可能會創建兩個關係:順便說一下

this.HasRequired(x => x.ContentType) 
    .WithMany(y => y.ContentTypeColumns) 
    .HasForeignKey(x => x.ContentTypeId); 

。這個映射根本不需要,因爲它是通過默認約定自動發現的。

+0

工作正常!非常感謝 :) – Kassem