2012-03-05 75 views
0

我使用EF4.3創建1至1間... 0的關係,但它扔EF4.3創建一對一或零關係失敗

異常「操作失敗,因爲索引或與名稱統計 'IX_id' 已經在表 'TestAs'」

的代碼存在如下

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (myContext context = new myContext()) 
      { 
       TestA tA = new TestA(); 
       TestB tB = new TestB(); 
       TestC tC = new TestC(); 
       context.testA.Add(tA); 
       context.testB.Add(tB); 
       context.testC.Add(tC); 
       context.SaveChanges(); 
      } 
     } 
    } 

    class TestA 
    { 
     public int id { get; set; } 
     //public TestB NavB { get; set; } 
     //public TestC NavC { get; set; } 
    } 

    class TestB 
    { 
     public int id { get; set; } 
     public TestA NavA { get; set; } 
    } 

    class TestC 
    { 
     public int id { get; set; } 
     public TestA NavA { get; set; } 
    } 

    class myContext : DbContext 
    { 
     public DbSet<TestA> testA { get; set; } 
     public DbSet<TestB> testB { get; set; } 
     public DbSet<TestC> testC { get; set; } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<TestB>().HasOptional(x => x.NavA).WithRequired(); 
      modelBuilder.Entity<TestC>().HasOptional(x => x.NavA).WithRequired(); 
     } 
    } 
} 

任何人都可以幫助嗎?通過WithOptionalPrincipalOnModelCreating方法

+0

哪個實體是這裏的原理? – Eranga 2012-03-05 09:26:33

+0

嗨Eranga,TestB和TestC是原理實體 – James 2012-03-05 09:32:13

+0

Then'TestA'不能與共享主鍵映射。該模型是無效的(實際) – Eranga 2012-03-05 12:14:16

回答

0

更換WithRequired

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<TestB>().HasOptional(x => x.NavA).WithOptionalPrincipal(); 
    modelBuilder.Entity<TestC>().HasOptional(x => x.NavA).WithOptionalPrincipal(); 
} 

(如果A是你使用WithOptionalDependent的主要實體。)

編輯

您的意見後,我認爲看到添加兩個類TestD和TestE的效果會很有趣,給出兩個導航屬性TestD和TestE,然後執行此操作在你的模型:

modelBuilder.Entity<TestB>().HasOptional(x => x.NavA).WithOptionalPrincipal(); 
modelBuilder.Entity<TestC>().HasOptional(x => x.NavA).WithOptionalPrincipal(); 
modelBuilder.Entity<TestA>().HasRequired(x => x.NavD); 
modelBuilder.Entity<TestA>().HasRequired(x => x.NavE); 

表A目前擁有四個外資鍵:B和C(可爲空),以d和E(不能爲空)。我認爲後者是你想要的。

+0

嗨GertArnold,代碼似乎修改我的關係。如果我的代碼中只有TestA和TestB,一切運行良好,但是在將TestC添加到代碼中後,表「TestA中已存在索引」異常被拋出。任何想法? – James 2012-03-07 08:11:22

+0

將TestC添加到code_中意味着什麼? – 2012-03-07 08:29:15

+0

請看我最初的帖子,如果代碼中沒有TestC類,只有TestA和TestB,請評論「modelBuilder.Entity ().HasOptional(x => x.NavA).WithOptionalPrinciple();」,代碼工作,但如果代碼是像最初的帖子,它不能工作 – James 2012-03-07 08:37:08