实体框架POCO - 更新集合

时间:2012-07-11 19:57:51

标签: c# entity-framework c#-4.0 entity-framework-4 entity-framework-4.1

我有一个简单的模型,其中包含名为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"))

谢谢Gonzalo

1 个答案:

答案 0 :(得分:1)

请将地址属性更改为ICollection。然后,在更新详细信息时,请检查EntityState是否已被deatched。如果它已分离,则必须将更新的对象(Customer和Address)附加到上下文中,并且必须告诉ObjectStateManager该对象已被修改。