English 中文(简体)
确保实体框架总是从数据库中读取?
原标题:Make sure Entity framework always reads from database?

我有这个应用程序,实际上是两个应用程序,一个web应用程序和一个控制台应用程序。控制台应用程序在windows机器上用作计划任务,每天执行3次以完成一些重复性工作。这两个应用程序都使用相同的模型和存储库,它们被放置在一个单独的项目(类库)中。问题是,如果控制台应用程序需要对数据库进行som更改,它会更新模型实体并将更改保存到数据库,但当这种情况发生时,webba应用程序中的上下文并不知道这一点,因此对象上下文不会用新的/更新的数据刷新,应用程序的用户也看不到更改。

我的问题是:有没有一种方法可以告诉对象上下文始终从数据库加载数据,无论是在孔对象上下文上还是针对特定查询?

/向Vinblad致以问候

最佳回答

我认为你不应该在web应用程序中遇到这个问题。web应用程序中的ObjectContext应该根据请求创建,因此只有更新期间的请求处理才会受到影响。

无论如何,很少有方法可以强制ObjectContext重新加载数据。查询和加载函数允许传递MergeOption,MergeOption应该能够覆盖当前数据。但最有趣的应该是Refresh方法,尤其是使用此应用程序

问题回答

通过使用DbSet,您还可以使用.AsNoTracking()方法。

每当你跑步时

context.Entities.FirstOrDefault()

或者无论对上下文进行什么查询,数据实际上都是从数据库中提取的,所以您不应该有问题。

What is your ObjectContext lifetime in the webapp? The ObjectContext is a UnitOfWork, so it should be only created to fetch/write/update data and disposed quickly afterwards. You can find a similar question here:

刷新ObjectContext还是重新创建它以反映对数据库所做的更改

FWIW,在查询中创建一个新的(匿名)对象也会强制往返数据库:

  queries from memory    
context.Entities.FirstOrDefault()

  queries from db
context.Entities.Select(Function(x) New With {p.ID, p.Name}).FirstOrDefault()

请原谅VB,它是我的母语:)





相关问题
Entity Framework with MySQL connector in c#

I have been trying to get the Entity Framework to work in my web application using MySQL. It works fine on my local pc, but doesn t work when I put it on the server. Since the server is a shared ...

How Do I Create And Update A Many To Many Relationship With EF

I am using the Entity Framework with SQL Server. I have a many to many relationship between 2 tables. I have created a join table with just the primary key fields of the 2 tables. In the designer, the ...

Entity Framework with File-Based Database

I am in the process of developing a desktop application that needs a database. The application is currently targeted to SQL Express 2005 and works wonderfully. However, I m not crazy about having ...

Linq to enties, insert foreign keys

I am using the ADO entity framework for the first time and am not sure of the best way of inserting db recored that contain foreign keys. this is the code that i am using, I would appreciate any ...

Entity Framework - Many to many question

I have a table called ASB and a table called PeopleInvolved. There is a junction table called PeopleInvolved_ASB which simply contains an ASBID and a PeopleInvolvedID column. The columns act as a ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

ADO.NET Entity Data Model are not precise enough

I run this code: var cos = from k in _db.klienci_do_trasy where k.klient_id == 5 select k; but the query send to database is: SELECT * FROM `klienci_do_trasy` LIMIT 0, 30 why is it for, there ...

热门标签