i have a simple model with classes named customer and address like this:
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; }
}
I wrote a unit test that loads a customer with an existing address, modifies that address and calls update. Here's the code:
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 is a reference to a class that inherits from DBContext. I'm getting this error:
A relationship from the 'Address_Customer' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Address_Customer_Source' must also in the 'Deleted' state.
What am i missing? Is it a problem with the way i'm defining the relationship between Customer and Address in OnModelCreating method? I'm doing this:
modelBuilder.Entity<Address>()
.HasRequired(p => p.Customer)
.WithMany(p => p.Addresses)
.Map(x => x.MapKey("CustomerID"))
Thanks, Gonzalo