只读 LINQ to SQL

发布于 2024-09-19 22:57:11 字数 74 浏览 1 评论 0原文

我正在使用 LINQ to SQL 访问我的数据库,但我只是阅读,从不插入、更新或删除任何内容。有没有办法为此优化 LINQ2SQL?

I'm using LINQ to SQL to access my database but I'm only reading, I never insert, update or delete anything. Are there ways to optimize LINQ2SQL for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尛丟丟 2024-09-26 22:57:11

是的,有。默认情况下,Linq 2 SQL 将缓存您从数据库读取的所有数据。它需要这样做来跟踪您应用于对象的任何更改,因此当您调用 SubmitChanges() 时它可以生成必要的插入/更新/删除语句。

如果您只是读取数据,则这是不必要的。您可以通过设置 ObjectTrackingEnabled< 来关闭对象跟踪DataContext 上的 /a> 属性设置为 false。

Yes there is. Linq 2 SQL will by default cache all data that you read from the DB. It needs to do this to track any changes you apply to your objects, so it can generate the necessary insert/update/delete statements when you call SubmitChanges()

If you're only reading data, this is unnessecary. You can turn off object tracking by setting the ObjectTrackingEnabled property to false on your DataContext.

来世叙缘 2024-09-26 22:57:11

我被告知的一件事是避免使用生成的记录类。

也就是说,如果您有一个 Users 表,L2S 将为您创建一个 User 类,这是它从数据库返回的内容。您应该创建一个“影子”类,而不是直接使用它——所有相同的属性,但没有其他内容,并立即将数据复制到这些记录中以供您使用。事实上,如果它是独占只读的,您可以在 ctor 中分​​配它们,并且只有公共 getter:

class myUser
{
   public string FName {get; private set}
   public string LName {get; private set}
   public myUser(User user)
   {
       this.FName = user.FName;
       this.LName = user.LName;
   }
}



var users = from u in db.Users
            where .....
            select new myUsers(u);

这避免了处理再次写出对象的可能性所需的大量开销。

One thing I've been told, is to avoid using the generated record class.

That is, if you have a Users table, L2S will create for you a User class, which is what it returns from the database. Instead of using that directly, you should create a "shadow" class --- all the same Properties, but nothing else, and immedaitely copy the data into those records for your use. In fact, if it's going to be exclusively read-only, you can assign them in the ctor, and only have public getters:

class myUser
{
   public string FName {get; private set}
   public string LName {get; private set}
   public myUser(User user)
   {
       this.FName = user.FName;
       this.LName = user.LName;
   }
}



var users = from u in db.Users
            where .....
            select new myUsers(u);

This avoids a lot of overhead needed to deal with the possibility of writing the object out again.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文