من 3تا جدول زیر رو در بانک ساختم :
و کلاسها به صورت زیر تعریف کردم:
public class Tb1
{
public Tb1()
{
ListTb2 = new List<Tb2>();
}
public int Id { get; set; }
public string NameTb1 { get; set; }
public virtual ICollection<Tb2> ListTb2 { get; set; }
}
public class Tb2
{
public Tb2()
{
ListTb1 = new List<Tb1>();
}
public int Id { get; set; }
public string NameTb2 { get; set; }
public virtual ICollection<Tb1> ListTb1 { get; set; }
}
و همینطور mapping :
public class Tb1Map : EntityTypeConfiguration<Tb1>
{
public Tb1Map()
{
this.HasKey(x => x.Id);
this.HasMany(x => x.ListTb2)
.WithMany(xx => xx.ListTb1)
.Map
(
x =>
{
x.MapLeftKey("Tb1Id");
x.MapRightKey("Tb2Id");
x.ToTable("Tb1Tb2");
}
);
}
}
public class Tb2Map : EntityTypeConfiguration<Tb2>
{
public Tb2Map()
{
this.HasKey(x => x.Id);
}
}
موقعی که در برنامه به صورت زیر استفاده میکنم:
var sv1 = new TableService<Tb1>(_uow);
var sv2 = new TableService<Tb2>(_uow);
var t1 = new Tb1 { NameTb1 = "T111" };
sv1.Add(t1);
//var res1= _uow.SaveChanges();
var t2 = new Tb2 { NameTb2 = "T222" };
sv2.Add(t2);
//var res2 = _uow.SaveChanges();
t1.ListTb2.Add(t2);
var result = _uow.SaveChanges();
هنگام SaveChanges این خطا رو میده:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
همراه با innerException زیر:
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Tb1Tb2_Tb2\". The conflict occurred in database \"dbTest\", table \"dbo.Tb2\", column 'Id'.\r\nThe statement has been terminated."}
در واقع همینطور که مشخصه من میخوام اون جدول رابطه رو در codeFirst حذف کنم یجورایی و رابطه رو بین 2 جدول اصلی بیارم. کجای کارم اشتباهه؟ و راهکارش چیه؟
من با پروفایلر هم نگاه کردم همه چی تا آخر داره پیش میره!
(آیا ForeignKey رو باید طور دیگه ای تعریف کنم؟)
با تشکر