Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

c# - 存储库模式EF核心更新方法(Repository Pattern EF Core Update method)

I have a question about using the Repository Pattern and Unit of Work pattern in a MVC Web Application with Entity Framework Core.

(我有一个关于在带有Entity Framework Core的MVC Web应用程序中使用存储库模式和工作单元模式的问题。)

I am currently implementing the update functionality in the controller.

(我目前正在控制器中实现更新功能。)

Now, at this point I am not sure what the best way is to update the entity.

(现在,我不知道最好的方法是更新实体。)

I have watched some videos where they said that an Update method should not be present in a repository like this:

(我看了一些视频,他们说更新方法不应出现在这样的存储库中:)

public T Update(T entity)
{
  DbSet.Attach(entity);
  var entry = Context.Entry(entity);
  entry.State = System.Data.EntityState.Modified;
}

So that means that I will have to do it like this in the controller:

(因此,这意味着我将必须在控制器中这样做:)

public IActionResult Edit(int id, [Bind("NeighbourhoodGroup,Neighbourhood,NeighbourhoodId")] Neighbourhoods neighbourhoods)
{
  var neighbourhoodsFound = unitOfWork.Neighbourhoods.Get(id);
  neighbourhoodsFound.Neighbourhood = neighbourhoods.Neighbourhood;
  neighbourhoodsFound.NeighbourhoodGroup = neighbourhoods.NeighbourhoodGroup;
}

However, that means that I will have to do this in all controllers, even if the object has alot of Properties?

(但是,这意味着即使对象具有很多属性,我也必须在所有控制器中执行此操作?)

I hope someone can give me some advice on what the best approach would be.

(我希望有人能给我一些关于最佳方法的建议。)

  ask by Azzaronn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your repository you can have the update functionality as simple as this:

(在您的存储库中,您可以具有以下简单的更新功能:)

public void Update(T entity)
    {
        DbSet.Attach(entity);
        ApplicationContext.Entry(entity).State = EntityState.Modified;
    }

While in the controller or from wherever you prefer to do your update you can get the entity preferably by id, modify all the properties that you want to modify on entity, call the the Update method from the repository which is going to set its state to modified and finally call the Save or SaveAsync method on the EF context.

(在控制器中或您希望从任何地方进行更新时,最好通过id获得实体,修改要在实体上修改的所有属性,从存储库中调用Update方法,它将状态设置为修改并最终在EF上下文上调用Save或SaveAsync方法。)

Your EF context should be exposed in your UnitOfWork.

(您的EF上下文应在UnitOfWork中公开。)

For more detailed explanation you can see this post, it will be very helpful.

(有关更详细的说明,您可以查看这篇文章,这将非常有帮助。)

EF Repository Pattern

(EF储存库模式)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...