2011-12-05 147 views
3

考慮以下簡化模型:實體框架代碼優先一對一約束衝突

public class Account 
{ 
    public Account() 
    { 
     Id = Guid.NewGuid(); 
     ContactCard = new ContactCard(); 
    } 

    //[ForeignKey("ContactCard")] 
    public Guid Id { get; set; } 
    public string Name { get; set; } 
    public string Number { get; set; } 
    public ContactCard ContactCard { get; set; } 
} 

public class ContactCard 
{ 
    public ContactCard() 
    { 
     Id = Guid.NewGuid(); 
    } 

    public Guid Id { get; set; } 
    public Account Account { get; set; } 
} 

public class MightDbContext: DbContext 
{ 
    public DbSet<Account> Accounts { get; set; } 
    public DbSet<ContactCard> ContactCards { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Account>().HasRequired(x => x.ContactCard).WithOptional(x => x.Account); 
    } 
} 

public class MightDbInitializer : DropCreateDatabaseIfModelChanges<MightDbContext> 
{ 
    protected override void Seed(MightDbContext context) 
    { 
     var accounts = new List<Account> 
     { 
      new Account() 
      { 
       Name = "Acme Corporation Pty. Ltd.", 
       Number = "001ABC" 
      }, 

      new Account() 
      { 
       Name = "Three Little Pigs Pty. Ltd.", 
       Number = "002DEF" 
      } 
     }; 

     accounts.ForEach(c => context.Accounts.Add(c)); 
    } 
} 

而下面這個簡單的控制檯程序遍歷帳戶的內容,並ContactCards集合:

static void Main(string[] args) 
    { 
     Database.SetInitializer<MightDbContext>(new MightDbInitializer()); 

     using (var context = new MightDbContext()) 
     { 
      foreach (Account c in context.Accounts) 
      { 
       Console.WriteLine(c.ContactCard.Id); 
      } 

      var contactCards = context.ContactCards.ToList(); /* ERROR OCCURS HERE */ 

      foreach (ContactCard a in contactCards) 
      { 
       Console.WriteLine(a.Id); 
      } 
     } 

     Console.Read(); 
    } 

爲什麼當我嘗試訪問ContactCards集合時,是否會收到以下錯誤:

Multip侵犯了合法性約束。關係「InvestAdmin.Might.DataAccess.Account_ContactCard」的角色「Account_ContactCard_Source」具有多重性1或0..1。

當我看到實際存儲在數據庫表中的數據似乎都是正確的。其實這裏是數據:

Accounts: 
Id Name Number 
ab711bad-1b32-42ca-b68b-12f7be831bd8 Acme Corporation Pty. Ltd. 001ABC 
dc20a1dd-0ed4-461d-bc9c-04a85b555740 Three Little Pigs Pty. Ltd. 002DEF 

ContactCards: 
Id 
dc20a1dd-0ed4-461d-bc9c-04a85b555740 
ab711bad-1b32-42ca-b68b-12f7be831bd8 

而對於完整性這裏是在數據庫中定義的Account_ContactCard外鍵約束:

-- Script Date: 06/12/2011 7:00 AM - Generated by ExportSqlCe version 3.5.1.7 
    ALTER TABLE [Accounts] ADD CONSTRAINT [Account_ContactCard] FOREIGN KEY ([Id]) REFERENCES [ContactCards]([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION; 

我一直在閱讀我只能在定義一對一的關係在Code First中嘗試了許多不同的配置。所有的事情都回到了同樣的問題。

回答

2

我發現我可以通過將創建關聯的ContactCard從Account構造函數移動到DBInitializer的Seed方法中的Account對象的實際創建來解決此問題。因此,它似乎不是(直接)一對一關係的問題。

+0

這指出我在正確的方向。我在構造函數中實例化一個導航屬性。我認爲這將被E.F覆蓋,但顯然不是。一旦我刪除了,我不再收到錯誤消息。謝謝 –

+0

@John Mc,對我來說,刪除construrctor的財產是生命的救星 – DEBAL