实体框架重复结果 [英] Entity Framework repeats results

查看:61
本文介绍了实体框架重复结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi
我已经使用Linq to SQL很长一段时间了,但是现在,因为我需要使用MySQL,我必须从Entity FrameWork开始。

我结合使用ADO.NET和EF和我没有意识到这个问题,但最近,我发现了一个非常大的问题,它让我发疯。



一个简单的查询.. 。



Dim Query =(从db.products中的p选择p).ToList



它给出了结果第一次好,但是当我再次运行这个查询时,它一次又一次地给出了相同的结果!!!



我的意思是,数据库中的任何变化它没有反映在该查询中。唯一的办法是退出程序并再次运行。



Visual Basic - VS2013

实体框架5.0(MySql)



谢谢。

Hi I have used Linq to SQL for a long time, but now, because I need to work with MySQL I had to start with Entity FrameWork.
I combine ADO.NET and EF and I did not realize about this issue, but recently, I had found a very big problem that it`s driving me crazy.

A simple query...

Dim Query = (From p in db.products select p).ToList

It gives the results the first time good, but when I run this query again, it gives the SAME RESULTS again and again !!!

I mean, any change in the database it is not reflected in that query. The only way is to quit program and run again.

Visual Basic - VS2013
Entity Framework 5.0 (MySql)

Thanks.

推荐答案

你没有展示整个代码,但我认为你所做的是在你的应用程序启动时创建一个上下文实例,然后在你的应用程序存在之前永远不要销毁它。



不要这样做。在需要查询数据时创建上下文实例,然后在完成后处理上下文。



EF从数据库中缓存它看到的所有内容。如果您请求整个表,则实体跟踪器会加载表中的每条记录并在内存中重新水合。所有未来对该数据的请求都来自跟踪器,而不是数据库。



您的代码看起来应该更像:

You're not showing the entire ball of code, but what I think you're doing is creating a context instance when your app starts and then never destroying it until your app exists.

DO NOT DO THIS. Create a context instance when you need to query the data and then dispose the context when your done with in.

EF caches everything it sees from the database. If you request an entire table, the entity tracker loads every record in the table and rehydrates it in memory. All future requests for that data come from the tracker, not the database.

Your code should look more like this:
Dim result As IEnumerable(Of Product)
Using (context As MyDbContext = new MyDbContext())
    result = context.Products.ToList()
End Using


EF缓存您的数据库。

您的类应该实现 IDisposable接口。或者您可以定义使用EF上下文的范围。

EF caches your database.
Your class should implement IDisposable interface. Or you can define the scope for using the EF context.
Using (db As MyDbEntities = new MyDbEntities())
    result = contedbxt.Products.ToList()
End Using



我建议您使用每当您使用EF时,存储库模式。

使用EntityTypeConfiguration的实体框架的存储库模式 [ ^ ]





-KR


I'd suggesst you to use Repository Pattern whenever you're working with the EF.
Repository Pattern with Entity Framework using EntityTypeConfiguration[^]


-KR


这篇关于实体框架重复结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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