我有一个简单的模型,其中包含名为 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 方法中定义客户和地址之间的关系的方式有问题吗?我正在这样做:
modelBuilder.Entity<Address>()
.HasRequired(p => p.Customer)
.WithMany(p => p.Addresses)
.Map(x => x.MapKey("CustomerID"))
谢谢,贡萨洛