I am trying to define the many-to-many relationship explicitly. Explicitly, I mean that I define the middle object and configure it using the Fluent API. Below is my code:
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"); } }
For some reason, two foreign keys are created in the resulting ContentTypeColumn table. One of them is a key with a zero value, the other is invalid. I want only the last one to be generated, and I have no idea where the null key comes from.
Any thoughts?
source share