2012-11-11 59 views
2

我有這些模式在我的數據庫:EF代碼中的這種多對多關係有什麼不對?

Tb1: { Id:int , NameTb1:varchar(50) } 
Tb2: { Id:int , NameTb2:varchar(50) } 
Tb1Tb2 { Tb1Id:int , Tb2Id:int } 

顯然Tb1Tb2是一個關係表,我想定義EF代碼優先多對一對多的關係。

而這些實體類:

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; } 
} 

和映射:

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(); 

我得到這個錯誤:

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.

和內部異常是:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Tb1Tb2_Tb2". The conflict occurred in database "dbTest", table "dbo.Tb2", column 'Id'.

爲什麼我得到這個錯誤? 和解決方案是什麼? TNX

回答

0

我刪除

sv2.Add(t2); 

和它的工作