【发布时间】:2012-05-31 11:27:47
【问题描述】:
我目前使用的通用存储库类只能像这样更新单个表
public abstract class MyRepository<T> : IRepository<T>
where T : class
{
protected IObjectSet<T> _objectSet;
protected ObjectContext _context;
public MyRepository(ObjectContext Context)
{
_objectSet = Context.CreateObjectSet<T>();
_context = Context;
}
public IQueryable<T> GetAll()
{
return _objectSet.AsQueryable();
}
public IQueryable<T> Find(Expression<Func<T, bool>> filter)
{
return _objectSet.Where(filter);
}
public void Add(T entity)
{
_objectSet.AddObject(entity);
_context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);
_context.SaveChanges();
}
public void Update(T entity)
{
_context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
_context.SaveChanges();
}
public void Delete(T entity)
{
_objectSet.Attach(entity);
_context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted);
_objectSet.DeleteObject(entity);
_context.SaveChanges();
}
}
对于我的 EDMX 设计器生成的每个表类,我都会创建另一个这样的类
public class CustomerRepo : MyRepository<Customer>
{
public CustomerRepo (ObjectContext context)
: base(context)
{
}
}
对于我需要对特定表进行的任何更新,我会这样做:
Customer CustomerObj = new Customer();
CustomerObj.Prop1 = ...
CustomerObj.Prop2 = ...
CustomerObj.Prop3 = ...
CustomerRepo.Update(CustomerObj);
当我只更新名为 Customer 的特定表时,这非常有效。现在,如果我还需要更新另一个名为 Orders 的 Customer 的子表的每一行,我需要对 MyRepository 类进行哪些更改。订单表将有多个客户记录和多个字段的记录,例如 Field1、Field2、Field3。
所以我的问题是:1.) 如果我只需要根据条件更新 Orders 表的某些行的 Field1,并根据不同的条件更新其他一些行的 Field2,那么我需要做哪些更改?
2.) 如果没有这样的条件,并且所有子行都需要更新为所有行的相同值,那么我需要做什么更改?
感谢您抽出宝贵时间。期待您的意见...
【问题讨论】:
标签: c# linq linq-to-sql entity-framework-4 linq-to-entities