Linq to SQL:查询不会查看待处理的更改 [英] Linq to SQL: Queries don't look at pending changes

查看:65
本文介绍了Linq to SQL:查询不会查看待处理的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此问题.我有以下代码:

string[] names = new[] { "Bob", "bob", "BoB" };
using (MyDataContext dataContext = new MyDataContext())
{
    foreach (var name in names)
    {
        string s = name;
        if (dataContext.Users.SingleOrDefault(u => u.Name.ToUpper() == s.ToUpper()) == null)
            dataContext.Users.InsertOnSubmit(new User { Name = name });
    }

    dataContext.SubmitChanges();
}

...并插入所有三个名称("Bob","bob"和"BoB").如果这是Linq-to-Objects,则不会.

...and it inserts all three names ("Bob", "bob" and "BoB"). If this was Linq-to-Objects, it wouldn't.

我可以查看待处理的更改以及表中已有的内容吗?

Can I make it look at the pending changes as well as what's already in the table?

推荐答案

我认为一般来说这是不可能的.假设您进行了如下查询:

I don't think that would be possible in general. Imagine you made a query like this:

dataContext.Users.InsertOnSubmit(new User { GroupId = 1 });
var groups = dataContext.Groups.Where(grp => grp.Users.Any());

由于尚未提交插入操作,数据库对新用户一无所知(尚未),因此生成的SQL查询可能不会返回ID = 1的Group.在这种情况下尚未提交的插入操作将是获取整个Groups-Table(如果受查询影响,则可能会有更多表)并在客户端上执行查询,这当然是不可取的.我猜想L2S设计师认为,如果某些查询考虑了尚未提交的插入而其他查询则没有考虑,那么这是违反直觉的,因此他们选择从不考虑它们.

The database knows nothing about the new user (yet) because the insert wasn't commited yet, so the generated SQL query might not return the Group with Id = 1. The only way the DataContext could take into account the not-yet-submitted insert in cases like this would be to get the whole Groups-Table (and possibly more tables, if they are affected by the query) and perform the query on the client, which is of course undesirable. I guess the L2S designers decided that it would be counterintuitive if some queries took not-yet-committed inserts into account while others wouldn't, so they chose to never take them into account.

为什么不使用

foreach (var name in names.Distinct(StringComparer.InvariantCultureIgnoreCase))

在访问数据库之前过滤掉重复的名字?

to filter out duplicate names before hitting the database?

这篇关于Linq to SQL:查询不会查看待处理的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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