我正在尝试明确定义多对多关系。明确地说,我的意思是我正在定义中间实体并使用Fluent API对其进行配置。以下是我的代码:
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
表上创建了两个外键。一个是可以为空的外键,另一个是不可为空的。我只想生成后者,我不知道可以为空的密钥来自哪里。
有什么想法吗?
答案 0 :(得分: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);
顺便说一下。根本不需要这种映射,因为它是通过默认约定自动发现的。