Note that there are some explanatory texts on larger screens.

plurals
  1. PO Insert new object with existing object
    text
    copied!<p>I am new to EF 4 and this is what I have done so far:</p> <ul> <li>Create an edmx file based on my database</li> <li>Create a code generation for my objects (POCO). Now I have a model1.tt, when expanded I see al my classes</li> <li>Create a repository for each class, based on IRepository</li> </ul> <p>Now, I am working with two objects, A and B. Object A has a property of type B. In my winform I have a combo filled with objects of type B. When the save button is pressed, a new instance of class A is created and all the properties are set. The object B property is set as follows:</p> <pre><code>objectA.myObjectB = (objectB)cmbBObjects.selectedItem; </code></pre> <p>Then I create a repository for objectA and call the save method. In this save method I have this code±</p> <pre><code>public bool Save(ObjectA obj) { using(MyContext context = new MyContext()) { context.objectAs.AddObject(obj); context.SaveChanges(); } } </code></pre> <p>This code, does save a new entry to the database, but it is also creating a new record for object B! I don't want this, because object B already exists in the database! (I have selected this one from the combobox).</p> <p>This is how I fill my combobox:</p> <p>In the objectB repository:</p> <pre><code>public IList&lt;ObjectB&gt; GetAll() { using(MyContext context = new MyContext()) { IList&lt;ObjectB&gt; objects = context.objectBs.ToList(); return objects; } } </code></pre> <p>In my form:</p> <pre><code>ObjectBRepository rep = new ObjectBRepository(); IList&lt;ObjectB&gt; objects = rep.GetAll; cmbBObjects.Datasource = objects; // etc.. </code></pre> <p>So my question is, what do I have to do to save object A without creating a new record for objectB?</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