我有一个简单的模型,其中包含名为Customer和Address的类,如下所示:
感谢您,Gonzalo。
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");
上下文是指继承自DBContext类的类的引用。我得到了这个错误:
'Address_Customer' AssociationSet 中的关系处于 'Deleted' 状态。鉴于多重性约束,相应的 'Address_Customer_Source' 也必须处于 'Deleted' 状态。
我错过了什么吗?我在 OnModelCreating 方法中定义 Customer 和 Address 之间的关系时有问题吗?我正在做这个:
modelBuilder.Entity<Address>()
.HasRequired(p => p.Customer)
.WithMany(p => p.Addresses)
.Map(x => x.MapKey("CustomerID"))
感谢您,Gonzalo。