Linq to SQL: queries are not pending changes

Follow this question . I have the following code:

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();
}

... and he inserts all three names ("Bob", "Bob" and "BoB"). If it was Linq-to-Objects, it is not.

Can I view the pending changes, as well as what is already in the table?

+3
source share
4 answers

I do not think that this would be possible in general. Imagine you made this request:

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

(), , SQL- Id = 1. , DataContext - , "" (, , , ) , , , . , L2S , , , - , .

-

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

?

+2

-

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 });
        break;
    }
}
+1

, LINQ to SQL.

, , , , ( ) SubmitChanges, , .

EDIT: SubmitChanges , .

0

ChangeSet,

if(
    dataContext.Users.
        Union(dataContext.GetChangeSet().Inserts).
        Except(dataContext.GetChangeSet().Deletes).
        SingleOrDefault(u => u.Name.ToUpper() == s.ToUpper()) == null)

Users .

Of course, you may need to create a variable ChangeSetto prevent several function calls GetChangeSet, and you may need to appropriately pass the object in the collection to the appropriate type. In the Insert and Deletes collections, you can filter it using

...GetChangeSet().Inserts.Where(o => o.GetType() == typeof(User)).OfType<User>()...
0
source

Source: https://habr.com/ru/post/1721490/


All Articles