DbSet.Attach, what exactly does it do?
Follow the methods below:
public class User
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
}
public class DataContext : DbContext
{
DbSet<User> Users { get; set; }
}
public class Repository
{
DataContext db = new DataContext();
public User Attach1(User entity)
{
var ent = db.Entry&l开发者_C百科t;User>(entity);
ent.State = EntityState.Modified;
if (db.SaveChanges() > 0)
return ent.Entity;
return null;
}
public User Attach2(User entity)
{
return db.Users.Attach(entity);
}
}
Is there any difference between Attach1
and Attach2
?
Your Attach1
and Attach2
methods perform different things and it is not clear what you expect to do in these methods. When you attach an entity to EF it will be added to the context in Unchanged
state. If you modify the entity after attaching, then EF will track those changes and the entity will be in Modified
state.
Attach1
This method will attach an entity and mark it as modified. So the subsequent SaveChanges()
will update all the properties of the entity. Calling SaveChanges()
inside the Attach
method is not recommended since it does more than attaching.
Attach2
This method will attach the entity as Unchanged
.
精彩评论