Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use the entity framework to create a database and and the data access layer.
All seems to work fine, but now I do have a problem I am not able to solve. It seems I didn't understand something.

If I create an entity A and an entity B I do get two classes Aset and Bset. If they do have a relationship, for example I get an object of ASet in Bset, so. Best contains one Aset. This is exactly what I would like to have.

If I now, create an Aset and an included Bset, it creates a data set for Aset and Bset in the Database A and B.
But if I read the values again, I do get the same classes with the same content until I save it again. In case I save the changes a second time, I still do have Bset, which is updates, but it creates a second ASet. So, after I while I do have plenty of ASet objects in my database.

How can I make sure that I update Bset and do get all object-versions of Aset gets updates, instead of get new ASet created?

Any ideas?

My approach would be, to have a quite complex BSet with several ASets, change several values in this complex object via code or user changes by an UI and then to update all objects by a call of savechanges only via an update of BSet.

Thank you everybody!
Posted
Comments
Sinisa Hajnal 20-Oct-14 2:16am    
Why not have ACollection or List<A> or some other one B-to-many A structures?
je-wo 20-Oct-14 9:12am    
From my points of view, this is exactly what I do.

Bset does have a an object which is List automatically created by the entity framework. The problem is, that even if the Bset does have 5x objects of type Aset in the collection, after the Update in the DB, it doesn`t update the 5 existing Asets (which I would like to have). It updates the Bset, but creates 5 new Aset`s. So, after an update of Bset, I do have 10 Asets in the DB. 5x the old objects, but 5x new Aset objects.

How can I make sure that the original 5 Aset objects get used for an update, instead of creating new objects?
Nathan Minier 21-Oct-14 8:35am    
Here's some super-rough code.

public class MyContext : DbContext
{
...
public bool Save(BSet set)
{
foreach(var A in set.Asets)
{
this.Entry(A).State = EntityState.Modified;
}
this.entry(set).State = EntityState.Modified;
return this.saveChanges();
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900