LINQ2SQL:更新对象不是DataContext的创建 [英] Linq2SQL: Update object not created in datacontext

查看:112
本文介绍了LINQ2SQL:更新对象不是DataContext的创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当您更新LINQ2SQL对象从一个DataContext获取对象,并使用相同的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?

什么是更新尚未retreived由用于执行保存操作的一个DataContext的对象,最好的办法,也就是我使用flourinefx通过flex和asp.net从物体时回报之间的数据客户端保存,我不知道如何保存对象?

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.

推荐答案

要更新现有的,但断开连接的对象,你需要附加它来做数据上下文。这将重新使用现有的主键等,您可以控制​​如何处理changes-即视为肮脏,或者把干净和跟踪未来的变化,等等。

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.

Attach方法是在桌子上 - 即

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

ctx.Customers.Attach(customer); // optional bool to treat as modified

这篇关于LINQ2SQL:更新对象不是DataContext的创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆