对象是否能在不同的Linq2SQL的Context中混用(转)

先看段代码

private static void ErrorCannotAttachAddNonNewEntities()
        {
            Purchase purchase;
            using (NutShellDataContext db = new NutShellDataContext())
            {
                db.Log = Console.Out;
                var query = from p in db.Purchases
                            where p.ID == 1
                            select p;

                purchase = query.First() as Purchase;
                
            }

            try
            {
                using (NutShellDataContext db2 = new NutShellDataContext())
                {
                   
                    purchase.Description = "Bike1";
                    //System.NotSupportedException will be raised
                    //An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext.  This is not supported.
                    //System.Data.Linq.ChangeTracker+StandardChangeTracker.Track(MetaType, Object, Dictionary[ObjectObject], Boolean, Int32)
                    db2.Purchases.Attach(purchase);
                    db2.SubmitChanges();
                }
            }
            catch
            {
                Console.WriteLine("Exception is occured");
                Console.ReadLine();
            }

            Console.WriteLine("Update Successfully");
            Console.WriteLine(purchase.Description);
            Console.ReadLine();
        }

可以看出来Purchase先取出来,范围是Context DB, 然后在DB2中试图修改。

 

System.NotSupportedException is thrown,An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext

exception是在方法System.Data.Linq.ChangeTracker+StandardChangeTracker.Track(MetaType, Object, Dictionary[ObjectObject], Boolean, Int32)中抛出的。

用reflect观察这个方法后发现,微软判断了,对象有没有延迟加载的对象。

我的通俗理解是,当对象有外键时,他的关系是维护在前一个context的,但是你把这个对象企图用到其他context,会造成意料不到的结果。所以不允许这么做。

如果没有外键的对象,其实是可以跨context去操作的。

这种案例做常见在web service的调用中,取的时候和当客户端修改完以后提交服务器进行修改的时候,datacontext是不一样的。

出处:http://blog.csdn.net/niuniu23_1982/article/details/6875810

posted @ 2014-07-17 10:15  邹邹  Views(158)  Comments(0)    收藏  举报