I have two table like below:
[Table("MyFlashCard")]
public partial class MyFlashCard
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public MyFlashCard()
{
MyFlashCardPics = new HashSet<MyFlashCardPic>();
}
public int Id { get; set; }
public int? FaslID { get; set; }
public virtual FasleManJdl FasleManJdl { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MyFlashCardPic> MyFlashCardPics { get; set; }
}
[Table("MyFlashCardPic")]
public partial class MyFlashCardPic
{
public int Id { get; set; }
[ForeignKey("MyFlashCard")]
public int MyFlashCardId { get; set; }
public virtual MyFlashCard MyFlashCard { get; set; }
}
and a ModelBuilder:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyFlashCard>()
.HasMany(e => e.MyFlashCardPics)
.WithRequired(e => e.MyFlashCard)
.HasForeignKey(e => e.MyFlashCardId)
.WillCascadeOnDelete();
}
and when I add migration it will create the below code:
CreateTable(
"dbo.MyFlashCardPic",
c => new
{
Id = c.Int(nullable: false, identity: true),
MyFlashCardId = c.Int(nullable: false),
MyFlashCard_Id = c.Int(),
MyFlashCard_Id1 = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.MyFlashCard", t => t.MyFlashCard_Id)
.ForeignKey("dbo.MyFlashCard", t => t.MyFlashCard_Id1)
.ForeignKey("dbo.MyFlashCard", t => t.MyFlashCardId, cascadeDelete: true)
.Index(t => t.MyFlashCardId)
.Index(t => t.MyFlashCard_Id)
.Index(t => t.MyFlashCard_Id1);
I only have MyFlashCardId column in MyFlashCardPic table but it want to create another column like: MyFlashCard_Id, MyFlashCard_Id1
I want to know why this happens and how prevent it?
If I delete these columns from above migration,after creating database(with update-database command) it will throws below error when I want to use MyFlashCardPic entity
Invalid column name 'MyFlashCard_Id1' , Invalid column name 'MyFlashCard_Id'
and if I don't delete these columns from migration I have problem in editing flashcard that have pics like another question I have recently
How to find out context objects that one entity is attached to?
another point is that without
[ForeignKey("MyFlashCard")]
attribute it will create 3 index column and without
modelBuilder.Entity<MyFlashCard>()
.HasMany(e => e.MyFlashCardPics)
.WithRequired(e => e.MyFlashCard)
.HasForeignKey(e => e.MyFlashCardId)
.WillCascadeOnDelete();
in OnModeling it will create 4 index column
MyFlashCard&MyFlashCardPicwhich EF generates default FK naming instead of user-defined one (related_entity + _ + PK name). If there is already exist another relationship with same name, by default EF will add suffix numbers to avoid duplicate FK naming. You can try on another dummy project to find out this behavior.