NET*_*NET 9 c# entity-framework savechanges
我读过这篇文章,但仍然误解了关键时刻.我们不需要打电话
_context.SaveChanges()
Run Code Online (Sandbox Code Playgroud)
在每个删除/更新/ ...操作?
如果我更改任何实体的属性确实SaveChanges()提交结果到数据库或我必须手动设置EntityState.Modifyed?
这是我的代码:
public class Repository<T> : IRepository<T>
where T : class
{
private IDbContext _context;
public Repository(IDbContext context)
{
_context = context;
}
private IDbSet<T> DbSet
{
get
{
return _context.Set<T>();
}
}
#region IRepository<T> Members
public void Insert(T entity)
{
DbSet.Add(entity);
}
public void Delete(T entity)
{
DbSet.Remove(entity);
}
public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public IQueryable<T> GetAll()
{
return DbSet;
}
public T GetById(int id)
{
return DbSet.Find(id);
}
#endregion
}
public interface IDbContext
{
IDbSet<T> Set<T>() where T : class;
int SaveChanges();
void Dispose();
}
Run Code Online (Sandbox Code Playgroud)
你问:
我们不需要在每个删除/更新/...操作中调用 _context.SaveChanges() 吗?
不,我们不。调用时 Delete我们并没有真正删除该实体 - 我们将其标记为删除。
与 相同Update,尽管您不必执行任何其他操作即可对实体进行所需的更改。所有属性(由默认模板生成)都将实现INotifyPropertyChanged,以便它知道实体何时被修改。
所有实体(首先在数据库中 - 由默认模板自动生成)都有一个State属性。ObjectContext只要更改发生在 ObjectEntity 的范围内,该属性就会被维护。
例如
Customer c;
using(var context = new MyEntityContext())
{
c = context.Customer.FirstOrDefault(); //state is now Unchanged
c.Name = "new name"; // this set the State to Modified
//context.SaveChanges(); // will persist the data to the store, and set the State back to unchaged
}
//if we look at our customer outside the scope of our context
//it's State will be Detacth
Console.WriteLine(c.State);
Run Code Online (Sandbox Code Playgroud)
然后,您调用SaveChanges所有具有状态Added Deleted或将在本地事务中将Modified其更改保存到数据库的实体
编辑
如果一个实体被标记为删除,并且您尝试修改它 - 您将得到一个InvalidOperationException
| 归档时间: |
|
| 查看次数: |
10209 次 |
| 最近记录: |