Linq TO SQL查询等待插入的记录

时间:2018-05-08 19:56:18

标签: lambda linq-to-sql

我需要在DataContext中查询数据,并让它返回后端的内容以及任何挂起的更新和插入。获取待定更新很容易,L2S已经没有太多问题。但是未决的插入物是一种不同的野兽,并且在不同的情况下表现不同。

Data before any Update/Insert:
PersonKey  FirstName      LastName      DateOfBirth
1          RICHARD        JONES         NULL
2          PAUL           ROGERS        01/21/1945

    int key = 1;
    NtsSuiteDataContext DbContext = new NtsSuiteDataContext();
    Person newPerson = new Person
    {
        FirstName = "DAVID",
        LastName = "SMITH"
    };
    DbContext.Persons.InsertOnSubmit(newPerson);

    Person updatePerson = DbContext.Persons.First(p => p.PersonKey == key);
    updatePerson.DateOfBirth = new DateTime(1970, 1, 2);

    var personList = DbContext.Persons.ToList();

Data after any Update/Insert:
PersonKey  FirstName      LastName      DateOfBirth
1          RICHARD        JONES         01/02/1970
2          PAUL           ROGERS        01/21/1945

现在,我知道我可以查询DbContext.GetChangeSet()。插入这些类型的插入,但是在编写代码时为每个查询执行此操作会有点脏。

这里我有另一个例子,有链接表,两个不同的查询,一个返回插入的记录,没有。我有点理解,但是,为什么L2S能够在一个查询中获得我在这里创建的记录,而在另一个查询中却没有。

Data before any update/inserts
PersonContactKey    PersonKey     ContactKey  ContactTypeKey
1                   1             1           1

    Person person = DbContext.Persons.First(p => p.PersonKey == key);
    PersonContact newPersonContact = new PersonContact
    {
        ContactTypeKey = 1,
            Description = "(555) 111-2222
    };
    DbContext.PersonContacts.InsertOnSubmit(newPersonContact);
    person.PersonContacts.Add(newPersonContact);
    newContact.PersonContacts.Add(newPersonContact);

    var list1 = DbContext.PersonContacts.Where(pc => pc.Person.PersonKey == key).ToList();
    var list2 = DbContext.Persons.First(p => p.PersonKey == key).PersonContacts.ToList();


list1 only has only the one personcontact record that already exists.
list2 has both the existing personcontact record and the new record  created above. 

Data after any update/inserts (list1)
PersonContactKey    PersonKey     ContactTypeKey  Description
1                   1             1               (123) 456-7890

Data after any update/inserts (list2)
PersonContactKey    PersonKey     ContactTypeKey  Description
1                   1             1               (123) 456-7890
0                   1             1               (555) 111-2222

TIA有任何意见和帮助。我理解这是怎么回事,只是想有人有更好的方法来获取INSERTED记录,如果我在向DataContext发出SubmitChanges()之前重新查询这些实体。

0 个答案:

没有答案