Use this approach:
public class Company { public int Id { get; set; } public string Name { get; set;} private ICollection<User> _users; public ICollection<User> Users { get { return _users ?? (_users = new HashSet<User>()); } set { _users = value; } } }
HashSet better than other collections if you also override Equals and GetHashCode in your entities. He will handle duplicity for you. And more lazy collection initialization is better. I donβt remember it for sure, but I think I had some problems in one of my first EF test applications when I initialized the collection in the constructor and also used dynamic proxies for lazy loading and change tracking.
There are two types of objects: detached and attached. A specific object is already being tracked by context. Usually you get an attached object from a linq-to-entity request or call Create on DbSet . A detached object is not tracked by the context, but as soon as you call Attach or Add in the set to attach this entity, all related objects will also be added / added. The only problem you have to deal with when working with individual objects is that the related object already exists in the database, and you only want to create a new relationship.
The basic rule that you should understand is the difference between the Add and Attach method:
Add will link all the individual objects in the graph as Added => all related objects will be inserted as new.Attach will attach all the individual objects in the graph as Unchanged =>, you must manually say what was changed.
You can manually set the state of any attached object using:
context.Entry<TEntity>(entity).State = EntityState....;
When working with many-to-many-disabled ones, you usually should use these methods to build only relationships instead of inserting duplicate objects into the database.
In my own experience, working with individual object graphs is very difficult, especially after deleting relationships, and because of this, I always load entity graphs from the database and manually merge the changes into attached graphs, which can fully track all changes for me.
Remember that you cannot mix objects from different contexts. If you want to attach an object from one context to another, you must first explicitly remove the object from the first. Hope you can do this by setting its state to Detached in the first context.
source share