Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq2SQL: Update object not created in datacontext

Normally when you update an object in linq2sql you get the object from a datacontext and use the same datacontext to save the object, right?

What's the best way to update a object that hasn't been retreived by that datacontext that you use to perform the save operation, i.e. I'm using flourinefx to pass data between flex and asp.net and when object return from the client to be saved I don't know how to save the object?

   public static void Save(Client client)
    {
        CompanyDataContext db = new CompanyDataContext();
        Validate(client);
        if(client.Id.Equals(Guid.Empty))
        {
            //Create (right?):
            client.Id = Guid.NewGuid();
            db.Clients.InsertOnSubmit(client);
            db.SubmitChanges();
        }
        else
        {
            //Update:
            OffertaDataContext db = new OffertaDataContext();
            db.Clients.????

        }
    }

Update: different approaches to use Attach doens't work in this case. So I guess a reflection based approach is required.

like image 307
Niels Bosma Avatar asked Dec 31 '22 07:12

Niels Bosma


1 Answers

To update an existing but disconnected object, you need to "attach" it do the data context. This will re-use the existing primary key etc. You can control how to handle changes- i.e. treat as dirty, or treat as clean and track future changes, etc.

The Attach method is on the table - i.e.

ctx.Customers.Attach(customer); // optional bool to treat as modified
like image 106
Marc Gravell Avatar answered Jan 12 '23 04:01

Marc Gravell