在使用Entity Framework时,如何刷新工作单元 [英] How can I refresh Unit of Work when working with Entity Framework

查看:82
本文介绍了在使用Entity Framework时,如何刷新工作单元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



在我的项目中,我正在使用SQL数据库和实体框架。

我正在使用工作单元模式来管理不同的数据集并提交更改。

对象集创建如下:

Hello,

In my project I am working with an SQL database and entity framework.
I am using the Unit of Work pattern to manage the different data sets and commit changes to it.
The object sets are created as follows:

private IObjectSet<DataObject> dataObjects;
public IObjectSet<DataObject> DataObjects
{
    get
    {
        if (dataObjects == null)
        {
            dataObjects = context.CreateObjectSet<DataObject>();
        }
        return dataObjects;
     }
}



我的问题与更新工作单元中包含的数据集有关。首次创建数据集时,它们会正确填充数据库中的数据。



但是,当任何这些数据对象的任何属性从不同位置更改时,我的工作单元没有更新。当我现在尝试对(修改的)对象集执行查询时,结果基于来自数据库的数据,即使我的工作单元中的数据集仍包含旧的(未修改的)数据。



从查询中检索正确的对象(基于数据库),而检索到的对象中包含的数据(基于工作单元)是没有。



通过将


My question is related to the updating of the datasets that are contained in the Unit of Work. When first creating a data set, they are filled correctly with data from the database.

However, when any property of any of these data objects is changed from a different location, it is not updated in my Unit of Work. When I now try to execute a query on the (modified) object set, the result is based on the data from the database, even though the data set from my Unit of Work still contains the old (unmodified) data.

The correct object is retrieved from the query (as based on the database), while the data contained in the retrieved object (as based on the Unit of Work) is not.

By adding

context.Refresh(RefreshMode.StoreWins, dataObjects);

添加到ObjectSet,检索到正确的值,但我想知道这是否是最佳解决方案。



如何在运行时正确添加和删除对象的数据集,但对象属性的更改未在工作单元中注册。 br />


提前谢谢。

to the ObjectSet, the correct value is retrieved, but I wonder if this is the best solution.

How is it possible that objects are correctly added and removed from the data set at runtime, but changes to the object's properties are not registered in the unit of work.

Thank you in advance.

推荐答案

你应该处理你的上下文并在每次重新创建时重新创建它由UnitOfWork调用。上下文模型将被缓存,但第二级缓存将被该进程清除。



例如:



You should be disposing your context and recreating it every time it is called by your UnitOfWork. The context model will be cached, but the 2nd level cache will be cleared by that process.

For example:

public class UnitOfWork
{
    public IObjectSet<dataobject> DataObjects
    {
        get
        {
            using(var context = new MyContext())
            {
                return context.CreateObjectSet<dataobject>();
            }
         }
    }
}
</dataobject></dataobject>





你会看到有人说从上到下,上下文实例都很便宜。这也可以正确执行UoW模式,而不是让你的上下文膨胀。



As you'll see people say all over, context instances are cheap. This also enforces the UoW patter properly, rather than letting your context bloat.


这篇关于在使用Entity Framework时,如何刷新工作单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆