开发者

Can I have a dynamicly updated dataContext?

开发者 https://www.devze.com 2023-02-15 01:07 出处:网络
I use DataContexts for 90% of my data access. But if, for instance, User1 modifies a record and User2 query the DataContext, he won\'t see the modifications. So I recreate my DataContext EVERY time I

I use DataContexts for 90% of my data access. But if, for instance, User1 modifies a record and User2 query the DataContext, he won't see the modifications. So I recreate my DataContext EVERY time I acces data (before every LINQ to SQL use).

There must be a better way to query the tables! Either I h开发者_如何学运维ave to get DataContexts to be synchronized with the tables, either I have to find a way to directly query the tables.

Any help would be appreciated!

Thank you!


So I recreate my DataContext EVERY time I acces data (before every LINQ to SQL use). There must be a better way to query the tables!

No, there is no better way and there is no need for one.

Creating a DataContext is relatively cheap, the only expensive part is the Connection and that is handled by the ConnectionPool.

So you can just think and reason in terms of Queries (they are the real expense) and the alternative, caching resultsets.


You can clear the cache in Linq2Sql as per the following blog post:

http://blog.robustsoftware.co.uk/2008/11/clearing-cache-of-linq-to-sql.html

The author also puts the code inside an extension method for us :)

Note: you will probably need to change the Context in the method signature. Once this has been done you can call db.ClearCache(); and it will all be lovely... tm.

I think there is another way of getting the data but can't remember where I found the information so may take me a while, will comment on this answer if i find it.

hth,

Stu


I believe that you may misunderstand the nature of the DataContext.

In most situtions, you'll want to create an instance of the DataContext with the Using statement. Within the Using statement you should then proceed to do your LINQ queries for your CRUD operations.

using (YourDataContext ctx = new YourDataContext()) {
    someTable stObj = (from st in ctx.someTable
                       select st).FirstOrDefault();

    stObj.SomeColumn = 1001;

    ctx.SaveChanges();
}

Any other DataContext that is opened after the DataContext above has been saved will see the changes that were made to SomeColumn.

0

精彩评论

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

关注公众号