Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework ObjectSet detach method functionality
    text
    copied!<p>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:</p> <pre><code>public class Company:EntityObject&lt;Int32&gt;, { public virtual string Name { get; set; } public virtual string Phone { get; set; } public virtual string Fax { get; set; } public virtual IList&lt;Customer&gt; Customers { get; set; } } public class Customer:EntityObject&lt;Int32&gt; { 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; } } </code></pre> <p>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:</p> <pre><code>using (IEntityModelContext context = new EFDataContext()) { var compFact = context.GetFactory&lt;Company&gt;(); var custFact = context.GetFactory&lt;Customer&gt;(); 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.CompanyRepository.Load(com =&gt; 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); </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload