首页 > 解决方案 > 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().Inserts 以获取这些类型的插入,但是为每个查询执行此操作在编写代码时会有点脏。

这里我有另一个例子,使用链接表,两个不同的查询一个返回插入的记录,一个不返回。我有点理解,但是,为什么 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 的任何意见和帮助。我明白这是怎么回事,只是想也许有人有更好的方法来获取插入记录,如果我在向 DataContext 发出 SubmitChanges() 之前重新查询这些实体。

标签: lambdalinq-to-sql

解决方案


推荐阅读