valerii.sverdlik
valerii.sverdlik

Reputation: 559

What is the best practice of updating entities in Linq2SQL?

Just wanted to understand what is the best practice of updating entities using linq2sql?

A bit more details to undestand the question better.

As I understood from the articles, I can have 2 situations: entity is attached to the context and entity constructed from the scratch(or from existing entity). I wanted to have only one method to update entites, that's implemented in the following way for now:

 public virtual void Save<T>(T value) where T : class
 {
      Context.GetTable<T>().Attach(value);
      Context.Refresh(RefreshMode.KeepCurrentValues, value);
      Context.SubmitChanges();
 }

Of course, when I execute the code:

var orders = GenericRepository.Instance.Find<BuyerOrder>(b => b.ID == 2).FirstOrDefault();
orders.Price = 397809;
GenericRepository.Instance.Save(orders); 

the object is already attached to the context and I got an exception:

Cannot attach an entity that already exists.

Should I always detach objects before saving? Is there another way to overcome this issue?

Sorry if the question is dumb - this is my first experiences with linq2sql

Upvotes: 0

Views: 183

Answers (2)

Silvermind
Silvermind

Reputation: 5944

You can check whether the entity is attached like this:

if (!Context.GetTable<T>().IsAttached(value))
{
    Context.GetTable<T>().Attach(value);
}
Context.Refresh(RefreshMode.KeepCurrentValues, value);
Context.SubmitChanges();

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56429

In your Save method, don't Attach the table. It also doesn't need to take a type, you can just call Context.SubmitChanges inside your Save method. Something like:

public void Save()
{
    Context.SubmitChanges();
}

Then do:

var orders = GenericRepository.Instance.Find<BuyerOrder>(b => b.ID == 2).FirstOrDefault();
orders.Price = 397809;
GenericRepository.Instance.Save(); 

See MSDN for some more examples: http://msdn.microsoft.com/en-us/library/bb386931.aspx

Upvotes: 1

Related Questions