1

If I retrieve an object from the database using Linq to SQL in one method using an instance of DataContext, which closes on exit of that method, can I edit the object in a different method and with a different DataContext and have the changes take effect in the database?

i.e. Would something like the below work?

public void Foo()
{
  using (var db = new DataContext())
  {
    Bar a = this.GetBar();
    if (a != null)
    {
      a.Property1 = true;
      db.SubmitChanges();
    }
  }
}

private Bar GetBar(string val)
{
  using (var db = new DataContext())
  {
    return db.FirstOrDefault(x => x.Property2 == val); 
  }
}
Fabiano
  • 5,124
  • 6
  • 42
  • 69
JChristen
  • 588
  • 4
  • 21
  • 1
    Possible duplicate of [How can I use two different data contexts in one LINQ request?](https://stackoverflow.com/questions/3447415/how-can-i-use-two-different-data-contexts-in-one-linq-request) – Jordy Dieltjens Jun 30 '17 at 12:18
  • 1
    @JordyDieltjens That seems to be across two different databases, whilst I'm asking about the same database, just different instances of DataContext – JChristen Jun 30 '17 at 13:12

1 Answers1

0

There should be some kind of Attach method

Something like:

public void Foo()
{
  using (var db = new DataContext())
  {
    Bar a = this.GetBar();
    if (a != null)
    {
      db.Bars.Attach(a);
      a.Property1 = true;
      db.SubmitChanges();
    }
  }
}
Pablo notPicasso
  • 3,031
  • 3
  • 17
  • 22