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<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
Attach1andAttach2methods 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 inUnchangedstate. If you modify the entity after attaching, then EF will track those changes and the entity will be inModifiedstate.Attach1
This method will attach an entity and mark it as modified. So the subsequent
SaveChanges()will update all the properties of the entity. CallingSaveChanges()inside theAttachmethod is not recommended since it does more than attaching.Attach2
This method will attach the entity as
Unchanged.