不反映存储库模式手动数据库更改 [英] Repository pattern manual db changes are not reflected

查看:69
本文介绍了不反映存储库模式手动数据库更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个用c#编写的MVC项目。我们使用实体框架与sql db连接。

我在项目中使用存储库模式和服务实现。手动db更新不反映获取存储库的查询。如何强制ef获取最新数据?



We have an MVC project which is written in c#. We are using entity framework to connect with sql db.
I use repository pattern with service implementation in our project. Manual db updates do not reflect to get queries of repository. How can I force ef get latest data?

private readonly ICompanyService companyService;
        public HomeController(ICompanyService companyService)
        {
            this.companyService = companyService;
        }
companyService.Get(id) -> this doesnt return updated company



我更新了应用程序运行时来自db的公司。

如果我使用此方法致电公司,则不会返回更新的数据。



仅适用用这种方式;


I updated company from db while app is running.
If I call the company with this method, updated data is not returned.

It only works with this way;

ServiceFactory.Services.CompanyService.Get(id)





ServiceFactory-> CompanyService是



ServiceFactory-> CompanyService is

private ICompanyService _companyService;
        public ICompanyService CompanyService
        {
            get
            {
                return _companyService ?? (_companyService =
                    new CompanyService(dbFactory, companyRepository, companyCustomerRepository,
                    regionCountryRepository, countryRepository, zoneRepository, unitOfWork));
            }
        }





我的尝试:



我只能在不使用服务实现的情况下执行此操作



What I have tried:

I can only do this without using service implementation

推荐答案

听起来你使用的是单个整个应用程序中的DbContext 实例。



一旦实体被 DbContext 实例加载,它将在该实例的生命周期内被缓存。除非您通过更改跟踪器手动强制刷新,否则从该实例读取该实体的任何尝试都将返回缓存的值,忽略数据库中的任何更改。



< a href =http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/>实体框架缓存Busting | Codethug [ ^ ]



对于Web应用程序,您应该为每个请求使用新的 DbContext 实例。如何执行此操作取决于您正在使用的IoC容器。
It sounds like you're using a single DbContext instance across the entire application.

Once an entity has been loaded by a DbContext instance, it will be cached for the lifetime of that instance. Any attempt to read that entity from that instance will return the cached value, ignoring any changes in the database, unless you manually force a refresh via the change tracker.

Entity Framework Cache Busting | Codethug[^]

For a web application, you should be using a new DbContext instance per request. How you do this will depend on which IoC container you're using.


这篇关于不反映存储库模式手动数据库更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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