开发者

Entity framework: How can I use more then one context?

I'm new with EntityFramework.

My application has a pool of context object instances (Each context has 1 connection to the DB).

The problem is that when I update an object (and calling SaveChanges), the data is updated in the DB and in the updating context but when I select from other instance, it gets the old data of the selected object.

Example:

Let's imagine a table called tbl.开发者_如何学运维

The table has 2 columns: id and data.

There is 1 row: id = 1, data = 2.

EFContext context1 = new EFContext();

EFContext context2 = new EFContext();

var obj1 = context1.tbl.Where(a => a.id == 1);

var obj2 = context2.tbl.Where(a => a.id == 1);

obj2.data = 10;

context2.SaveChanges();

var obj3 = context1.tbl.Where(a => a.id == 1);

After executing these lines, obj3.data contains 2, instead of 10.

How can I solve this problem?

I don't want to create a context instance every time I want to access the DB.

Thanks!


I think Refreshing your entity should do the trick, like this:

//after
context2.SaveChanges();

//refresh obj1
context1.Refresh(RefreshMode.StoreWins, obj1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜