Entity framework 仅使用DbSet更新对象

Entity framework 仅使用DbSet更新对象,entity-framework,dbcontext,dbset,Entity Framework,Dbcontext,Dbset,我试图应用中描述的工作单元模式,但遇到了以下问题:如果我只将关联的DbSet注入repo,例如 public ArticleRepository(DbSet<Article> articles) { this.articles = articles; } 但是使用新方法,我不再能够访问DbContext。DbSet.Add和DbSet.Attach在这里都不起作用,因此如何在上下文中更新对象?System.Data.Entity.Migrations.IDbSetExtens

我试图应用中描述的工作单元模式,但遇到了以下问题:如果我只将关联的DbSet注入repo,例如

public ArticleRepository(DbSet<Article> articles)
{
   this.articles = articles;
}

但是使用新方法,我不再能够访问DbContext。DbSet.Add和DbSet.Attach在这里都不起作用,因此如何在上下文中更新对象?

System.Data.Entity.Migrations.IDbSetExtensions包含IDbSet扩展AddOrUpdate
。这将更新实体

有些人喜欢不知道自己是在添加新实体还是在更改现有实体的优势

但是,如果您确实希望在更新尚未添加的项时出错,请查看

在这里,您可以看到函数首先检查项目是否存在,并根据结果添加或更新项目,如下所示:

var existing = set.SingleOrDefault
    (Expression.Lambda<Func <TEntity, bool>> (matchExpression, new[]
        {parameter}));

if (existing != null)
{   // entity exists: update it
    foreach (var keyProperty in keyProperties)
    {
        keyProperty.Single().SetValue
            (entity, keyProperty.Single().GetValue (existing, null), null);
    }
    internalSet.InternalContext.Owner.Entry(existing)
        .CurrentValues.SetValues (entity);
}
else
{   // not existing entity: Add it
    internalSet.Add(entity);
}
var existing=set.SingleOrDefault
(Expression.Lambda(matchExpression,新[]
{参数});
if(现有!=null)
{//实体存在:更新它
foreach(keyProperties中的var keyProperty)
{
keyProperty.Single().SetValue
(实体,keyProperty.Single().GetValue(现有,null),null);
}
internalSet.InternalContext.Owner.Entry(现有)
.CurrentValues.SetValues(实体);
}
其他的
{//不存在实体:添加它
添加(实体);
}

如果您不想要AdOrdUpdate,但实际上只是一个更新,请考虑为IDBSET创建自己的扩展方法。请参见

IGenericRepository
完全由您设计。您可以添加一些方法来设置实体的状态。这种接口看起来真的像一个包装器。因此,如果可能,尝试通过其他隐藏接口公开核心部分(DbContext,…)。需要时,您可以随时访问core以执行某些高级任务。作为一个包装器,有时它不能像处理核心部件那样提供完整的操作。对我来说,这种模式很大程度上是基于所谓的包装器。您可以从
DbSet
访问上下文。2.不要注入
DbSet
,注入上下文本身,然后使用上下文设置
this.articles
。3.你知道你为什么要把上下文抽象出来吗?实体框架上下文已经具有内置的工作单元机制。
var existing = set.SingleOrDefault
    (Expression.Lambda<Func <TEntity, bool>> (matchExpression, new[]
        {parameter}));

if (existing != null)
{   // entity exists: update it
    foreach (var keyProperty in keyProperties)
    {
        keyProperty.Single().SetValue
            (entity, keyProperty.Single().GetValue (existing, null), null);
    }
    internalSet.InternalContext.Owner.Entry(existing)
        .CurrentValues.SetValues (entity);
}
else
{   // not existing entity: Add it
    internalSet.Add(entity);
}