在我以前的应用程序中,当我使用 linq-to-sql 时,我总是使用一个类来放入我的 linq-to-sql 代码,所以我只有一个 DataContext
。
虽然我当前的应用程序变得太大了,但我开始将我的代码分成不同的类(一个用于客户,一个用于位置,一个用于供应商......)并且它们都有自己的 DataContext DatabaseDesignDataContext dc =新的 DatabaseDesignDataContext();
现在,当我尝试使用某个位置(我从不同的 DataContext 获得)保存联系人时,出现以下错误:
"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."
我假设这是因为我为每个类创建了一个 DataContext
,但我不知道如何做?
我正在寻找任何想法,谢谢。
我的类(class)如下所示:
public class LocatieManagement
{
private static DatabaseDesignDataContext dc = new DatabaseDesignDataContext();
public static void addLocatie(locatie nieuweLocatie)
{
dc.locaties.InsertOnSubmit(nieuweLocatie);
dc.SubmitChanges();
}
public static IEnumerable<locatie> getLocaties()
{
var query = (from l in dc.locaties
select l);
IEnumerable<locatie> locaties = query;
return locaties;
}
public static locatie getLocatie(int locatie_id)
{
var query = (from l in dc.locaties
where l.locatie_id == locatie_id
select l).Single();
locatie locatie = query;
return locatie;
}
}
最佳答案
如果实体仍然附加到原始数据上下文,就会发生这种情况。关闭延迟加载(dc.DeferredLoadingEnabled = false):
partial class SomeDataContext
{
partial void OnCreated()
{
this.DeferredLoadingEnabled = false;
}
}
您可能还需要对其进行一次序列化/反序列化(例如使用 datacontractserializer)以将其与原始 DC 断开连接,这是使用 datacontractserializer 的克隆方法:
internal static T CloneEntity<T>(T originalEntity) where T : someentitybaseclass
{
Type entityType = typeof(T);
DataContractSerializer ser =
new DataContractSerializer(entityType);
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, originalEntity);
ms.Position = 0;
return (T)ser.ReadObject(ms);
}
}
关于c# - 从另一个 DataContext 加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9787819/