实体框架4 - 更新时重复密钥

时间:2012-01-04 00:08:32

标签: c# entity-framework-4 linq-to-entities

我在实体框架中执行更新时遇到问题。我真的不明白我所看到的行为。

我正在使用AdventureWorks数据库。

StateProvince的起始值为Micronesia。如果我将其更改为Maryland,则更新成功。但是,如果我尝试将其更改回Micronesia,则会收到以下错误:

  

“无法在对象'Sales.SalesTerritory'中插入重复的键行   唯一索引'AK_SalesTerritory_Name'。\ r \ n声明已经   终止“。

有问题的DAL方法是:

    public static void UpdateCustomer(CustomerDetails customerDetails)
    {
        AWEntities context = Common.GetContext();
        var customerQuery = from c in context.Individuals
                                .Include("Contact")
                                .Include("Customer.CustomerAddresses.Address.StateProvince.SalesTerritory")
                                //.Include("Customer.SalesTerritory.StateProvinces")
                                .Where(id => id.CustomerID == customerDetails.CustomerId)
                            select c;
        var individual = customerQuery.ToList().ElementAt(0);

        Contact contact = individual.Contact;
        contact.LastName = customerDetails.LastName;
        contact.MiddleName = customerDetails.MiddleName;
        contact.FirstName = customerDetails.FirstName;
        contact.EmailAddress = customerDetails.EmailAddress;
        contact.Phone = customerDetails.Phone;
        contact.Title = customerDetails.Title;

        AWModel.Customer customer = individual.Customer;
        customer.CustomerID = customerDetails.CustomerId;
        customer.SalesTerritory.Name = customerDetails.SalesTerritory;

        Address address = individual.Customer.CustomerAddresses.ElementAt(0).Address;
        address.AddressLine1 = customerDetails.AddressLine1;
        address.AddressLine2 = customerDetails.AddressLine2;
        address.City = customerDetails.City;
        address.PostalCode = customerDetails.PostalCode;
        address.StateProvinceID = customerDetails.SalesProvinceId;

        context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
    }

任何人都可以找到正确的方法来做我正在尝试的事情。

1 个答案:

答案 0 :(得分:1)

更新SalesTerritory.Name属性时会发生这种情况:

 customer.SalesTerritory.Name = customerDetails.SalesTerritory;

效果是更改SalesTerritory实体,而不是customer实体。我相信你想要更像的东西:

 customer.SalesTerritoryID = customerDetails.SalesTerritoryID;