簡體   English   中英

實體框架:添加新對象將導致重復

[英]Entity framework: adding new objects results in duplicates

我正在開發一個三層WinForms應用程序。 但是,當我嘗試向數據庫中添加新對象時,某些對象會重復。

類別:

class Customer 
{
    public int Id { get; set; }
    public int CustomerName { get; set; }

    public virtual IList<CustomerAccount> CustomerAccount { get; set; }
}

class CustomerAccount
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public int AccountId { get; set; }

    public virtual Customer Customer { get; set; }
    public virtual Account Account { get; set; }
}

class Account
{
    public int Id { get; set; }
    public int AccountName { get; set; }
}

這是我用來將Customer對象添加到數據庫中的代碼:

 DataContext.CustomerSet.Add(customer);
 DataContext.SaveChanges();

添加到客戶的帳戶是現有帳戶。 這些是在數據庫中重復的行。 因此,例如:

Customer c;
c.CustomerName = "Kevin";

c.CustomerAccount.Add(new CustomerAccount() {
    AccountId = existingAccountId,
    Account = existingAccount
}

AddCustomer(c);

在此示例中,existedAccount被復制。

我知道這與DataContext.Attach()方法有關。 但是,如果添加了多個CustomerAccount關系,那將不起作用。 (ObjectStateManager中已經存在具有相同鍵的對象。)

提前感謝。

不要創建CustomerAccount的新實例。 您必須從數據庫中重新加載它並使用Context中的對象。

    Customer c;
    c.CustomerName = "Kevin";

    var customerAccount = DataContext.CustomerAccount.First( c => c.AccountId == existingAccountId)


    c.CustomerAccount = customerAccount;
    DataContext.Customer.Add(c);
    DataContext.SaveChanges();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM