簡體   English   中英

實體框架POCO - 更新集合

[英]Entity framework POCO - Update collection

我有一個簡單的模型,其中包含名為customer和address的類,如下所示:

public class Customer : BusinessEntity
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime? DateOfBirth { get; set; }

    public decimal? CreditLimit { get; set; }

    public virtual List<Address> Addresses { get; set; }

    public string Email { get; set; }
}

public class Address : BusinessEntity
{
    public string Street { get; set; }

    public string Floor { get; set; }

    public Customer Customer { get; set; }
}

我寫了一個單元測試,用現有地址加載客戶,修改該地址並調用更新。 這是代碼:

        Customer newCustomer = new Customer();

        newCustomer.FirstName = "Cosme";

        newCustomer.LastName = "Fulanito";

        newCustomer.Email = "anemail@mail.com";

        customerPersistence.Save(newCustomer);

        Customer existingCustomer = customerPersistence.FindByID(newCustomer.ID.Value);

        Assert.IsNotNull(existingCustomer, "Customer not found after saving");

        existingCustomer.LastName = "Fulanito Modified";

        existingCustomer.Addresses = new List<Address>();

        existingCustomer.Addresses.Add(new Address { Customer = existingCustomer, Floor = "21", Street = "Peron" });

        customerPersistence.Update(existingCustomer);

        Customer loadedCustomer = customerPersistence.FindByID(newCustomer.ID.Value);

        Assert.IsNotNull(loadedCustomer, "Customer not found after updating");

        Assert.IsTrue(loadedCustomer.LastName == existingCustomer.LastName, "Last name not updated");

        Assert.IsNotNull(loadedCustomer.Addresses, "Addresses collection is null");

        Assert.IsTrue(loadedCustomer.Addresses.Count > 0, "Addresses collection is empty");

        existingCustomer = customerPersistence.FindByID(newCustomer.ID.Value);

        Assert.IsNotNull(existingCustomer, "Customer not found after updating");

        existingCustomer.Addresses[0].Floor = "40";

        customerPersistence.Update(existingCustomer);

        Assert.IsTrue(loadedCustomer.Addresses[0].Floor == "40", "Address data not modified");

Context是對從DBContext繼承的類的引用。 我收到這個錯誤:

來自“Address_Customer”AssociationSet的關系處於“已刪除”狀態。 給定多重約束,相應的'Address_Customer_Source'也必須處於'已刪除'狀態。

我錯過了什么? 這是我在OnModelCreating方法中定義Customer和Address之間關系的方式的問題嗎? 我這樣做:

modelBuilder.Entity<Address>()
            .HasRequired(p => p.Customer)
            .WithMany(p => p.Addresses)
            .Map(x => x.MapKey("CustomerID"))

謝謝,貢薩洛

請將地址屬性更改為ICollection。 然后,在更新詳細信息時,請檢查EntityState是否已被deatched。 如果它已分離,則必須將更新的對象(Customer和Address)附加到上下文中,並且必須告訴ObjectStateManager該對象已被修改。

暫無
暫無

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

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