Entity Framework ObjectSet detach method functionality
Well, first of all I'll explain the whole situation. I have simple POCO domain model which I'm persisting with EF 4.0. For the first time I used only navigation properties and no FK properties. But later due to some binding purposes I decided to add FK properties to my model (Company_ID in the code below). Here are two classes from that model:
public class Company:EntityObject<Int32>, {
public virtual string Name { get; set; }
public virtual string Phone { get; set; }
public virtual string Fax { get; set; }
public virtual IList<Customer> Customers { get; set; }
}
public class Customer:EntityObject<Int32> {
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual Company Company { get; set; }
public virtual int Company_ID { get; set; }
}
I simplified this model a little bit just to highlight the main issue. After adding FK properties I regenerated the EDMX with FK inclusion. So now some of my test code doesn't work anymore. The problem is with detach method of ObjectSet (Repository Detach is a wrapper around it). Here is the test code:
using (IEntityModelContext context = new EFDataContext()) {
var compFact = context.GetFactory<Company>();
var custFact = context.GetFactory<Customer>();
Company comp = compFact.CreateObject();
comp.Fax = "111111";
comp.Name = "Testcomp";
comp.Phone = "222222";
context.CompanyRepository.Add(comp);
context.SaveChanges();
Customer cust = custFact.CreateObject();
cust.FirstName = "John";
cust.LastName = "Smith";
comp.Customers.Add(cust);
context.SaveChanges();
context.CompanyRepository.Detach(comp);
Company newComp = context.CompanyReposi开发者_StackOverflowtory.Load(com => com.Name == "Testcomp");
Assert.IsNotNull(newComp);
Assert.IsFalse(newComp.IsTransient);
Assert.AreEqual(comp.Fax, newComp.Fax);
Assert.AreEqual(industryList.Values[0], newComp.Industry);
Assert.AreEqual(comp.Name, newComp.Name);
Assert.AreEqual(comp.Phone, newComp.Phone);
Assert.AreEqual(sizeList.Values[0], newComp.Size);
Assert.AreEqual(1, newComp.Customers.Count);
The problem rises when newComp object is loaded: Customers property is empty, moreover it's null (I checked the DB - Customer was successfully saved). So the last assertion fails. This code worked quite well until I added FK property. So is there any explanation of this behavior?
Assuming it was successfully saved to the db (so the customer/company relationship exists in db)
The problem lies in the fact that you did not load the reference to Customers. So either:
A) Include Customers when you retrieve company from the context, or
B) Lazy Load it before you check the reference.
精彩评论