0
我构建一个存储库就像Codefirst演示。entityframework搜索值只搜索不更新
public virtual IQueryable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query);
}
else
{
return query;
}
}
但是这个搜索有一个问题。
有时候其他人使用'get'函数来搜索值,这个值将被用作其他函数中的参数。
就像这样:
UserInfoBll userInfoBll = new UserInfoBll();
UserInfo userInfo = userInfoBll.Get(p => p.UserCode == "8001", null, "CorpShop").First();
ConsumeProcess.process(userInfo);
如果在功能ConsumeProcess.process USERINFO值的变化,当我处理savechange。
它会更新我不想更新的东西,所以我想找到一种方法。搜索值仅用于搜索,当值更改时,不更新值。
对于这样我写了这个:
public virtual List<TEntity> GetList(Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
List<TEntity> tEntityList = Get(filter, orderBy, includeProperties).ToList();
SetEntityStates(EntityState.Detached, tEntityList);
return tEntityList;
}
protected void SetEntityStates(EntityState entityState, IEnumerable<TEntity> tEntity_params)
{
foreach (TEntity tEntity in tEntity_params)
{
if (tEntity != null)
{
context.Entry(tEntity).State = entityState;
}
}
}
现在不会更新,如果有人改变了搜索的价值。但还有另一个问题。 如果我用这样的代码,其中包括财产不能得到
UserInfoBll userInfoBll = new UserInfoBll();
userInfo = userInfoBll.GetList(p => p.UserCode == "8001", null, "CorpShop").First(); // CorpShop is include property
corpShop = userInfo.CorpShop; //userInfo.CorpShop is null
你正在更新你不想更新的值吗?我想找到问题的根源,而不是像你在'GetList'方法中那样对抗症状。什么是“ConsumeProcess.process”呢? –
@Gert Arnold ConsumeProcess.process不会更改userInfo,但我不知道为什么当我启动savechange函数时。关于userInfo的更新sql已经执行。价值已经改变。所以我认为原因是搜索值的状态context.Entry(tEntity).State = EntityState.modify,所以我改变了状态,因为如果我想改变值,我应该处理更新函数,而不是改变get函数的值 – user2702915