I have these schema in my database:
Tb1: { Id:int , NameTb1:varchar(50) }
Tb2: { Id:int , NameTb2:varchar(50) }
Tb1Tb2 { Tb1Id:int , Tb2Id:int }
Obviously Tb1Tb2 is a relationship table and I want to define a many-to-many relationship in EF code-first.
And these are the entity classes :
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; }
}
and mappings :
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);
}
}
When I use it in my app :
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();
I get this error:
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.
and inner exception is:
The INSERT statement conflicted with the FOREIGN KEY constraint
“FK_Tb1Tb2_Tb2”. The conflict occurred in database “dbTest”, table
“dbo.Tb2”, column ‘Id’.
Why do I get this error?
and what is the solution?
tnx
I remove the
and it worked