2010-09-23 60 views
2

这可能已经被问过,但我找不到它,所以在这里。LinqToSql的关联加载

我们使用Context.GetTable()对表进行泛型读取,然后附加表达式以在表中找到单个记录。该表具有关联。不幸的是,我们试图改变一个关联的领域,所以;

富是酒吧的父母对FooId

当我们要改变FooId,它的崩溃,因为的EntityRef的HasAlreadyLoaded属性设置为true。除非我不太了解LinqToSql,否则我认为这是在此记录集上调用SingleOrDefault的行为,它实际上正在触发查询并因此加载所有关联的对象。

有没有办法阻止这种加载发生? (ObjectTrackingEnabled和DeferredLoading设置为true),如果不是这个问题常见的解决方案是什么?我们现在还不知道个人关系,我不想看看是否有可能找出关联并根据ID加载它们。

我的首选方法本来是一个不太通用的方法,我可以完成.Foo = Context.Foo.Select(x => x.Id == FooId),但我们现在没有那种奢侈。

回答

1

在LINQ to SQL中,要更新关联属性,必须将子对象从父母的父母的EntitySet<>移动到另一父母的EntitySet<>,并且在移动LINQ to SQL期间自动更新孩子的关联属性。

例如:

 // Get the source parent 
     Foo foo1 = context.Foos.Where(f => f.ID == 1).SingleOrDefault(); 
     Bar bar1 = foo1.Bars[0]; 

     // (Note: you don't necessarily need to get foo1 first - 
     // you could just get bar1 directly and proceed from here...) 

     // Get the destination parent 
     Foo foo2 = context.Foos.Where(f => f.ID == 2).SingleOrDefault(); 

     // Move the child over. LINQ to SQL automatically updates bar1.FooID from 1 to 2 here. 
     foo2.Bars.Add(bar1); 

     // Done. 
     context.SubmitChanges();