Reputation: 574
There two way to add new object into DBSet Code example: `
var entity= new EntityClass()
{
Id = 1,
Name = "Name"
};
//Way 1
_context.Entry(entity).State = EntityState.Added;
_context.SaveChanges();`
//Way 2
_context.EntityClasses.Add(entity);
_context.SaveChanges();
`
The question is: what different between these way. And which way we should use?
Upvotes: 2
Views: 39
Reputation: 1358
Here is detail on MSDN about your question as below:
A new entity can be added to the context by calling the Add method on DbSet. This puts the entity into the Added state, meaning that it will be inserted into the database the next time that SaveChanges is called. For example:
using (var context = new BloggingContext())
{
var blog = new Blog { Name = "ADO.NET Blog" };
context.Blogs.Add(blog);
context.SaveChanges();
}
Another way to add a new entity to the context is to change its state to Added. For example:
using (var context = new BloggingContext())
{
var blog = new Blog { Name = "ADO.NET Blog" };
context.Entry(blog).State = EntityState.Added;
context.SaveChanges();
}
Finally, you can add a new entity to the context by hooking it up to another entity that is already being tracked. This could be by adding the new entity to the collection navigation property of another entity or by setting a reference navigation property of another entity to point to the new entity. For example:
For more information, please access the below link http://msdn.microsoft.com/en-us/data/jj592676.aspx
Upvotes: 2