Reputation: 19356
When I want to delete a property, I have two options:
myDbContext.MyType.Add(myEntity);
myDbContext.MyType.Local.Add(myEntity);
In both cases, at least in my case, don't see differences, but I don't know really if it has a different behavior or not.
Is it really the same or not?
Thanks.
Upvotes: 1
Views: 307
Reputation: 2459
Based on documentation of methods:
myDbContext.MyType.Add(myEntity);
/// Begins tracking the given entity, and any other reachable entities that are
/// not already being tracked, in the <see cref="EntityState.Added" /> state such that
/// they will be inserted into the database when <see cref="SaveChanges()" /> is called.
myDbContext.MyType.Local.Add(myEntity);
/// <para>
/// Adds a new entity to the <see cref="DbContext" />. If the entity is not being tracked or is currently
/// marked as deleted, then it becomes tracked as <see cref="EntityState.Added" />.
/// </para>
/// <para>
/// Note that only the given entity is tracked. Any related entities discoverable from
/// the given entity are not automatically tracked.
/// </para>
The 2nd paragraph above specifies the difference between both the methods.
Essentially, the difference is, DbSet.Add
is recursive, it will add new dependent entities too. Local.Add
adds only current entity.
Example code:
Entity types:
public class Blog
{
public int Id { get; set; }
public IList<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
}
Case 1:
db.Blogs.Add(
new Blog
{
Posts = new List<Post>
{
new Post(),
new Post(),
}
}
);
db.SaveChanges();
var query = db.Set<Post>().Count(); //Output will be 2
Case 2
db.Blogs.Local.Add(
new Blog
{
Posts = new List<Post>
{
new Post(),
new Post(),
}
}
);
db.SaveChanges();
var query = db.Set<Post>().Count(); //Output will be 0
Upvotes: 1
Reputation: 73
myDbContext.MyType.Add(myEntity);
It will do following:
Adds the given entity to the context underlying the set in the Added
state such that it will be inserted into the database when SaveChanges
is called.
myDbContext.MyType.Local.Add(myEntity);
It will do the following:
Gets a System.Collections.ObjectModel.ObservableCollection
1` that represents a local view of all Added, Unchanged, and Modified entities in this set. This local view will stay in sync as entities are added or removed from the context.
Likewise, entities added to or removed from the local view will automatically be added to or removed from the context.
Remarks:
This property can be used for data binding by populating the set with data, for example by using the Load extension method, and then binding to the local data through this property. For WPF bind to this property directly. For Windows Forms bind to the result of calling ToBindingList on this property
Upvotes: 0