我正在编写一个类,它将(希望)允许通过linqtosql层操作数据,而不必知道使用的是哪个单独的对象。到目前为止,它在级联选择和插入方面工作得很好,但是我在更新方面遇到了困难。
下面是我使用的保存方法:
if ((long)entity.GetType().GetProperty(GetPrimaryKeyName(entity)).GetValue(entity, null) == 0)
{
Context.GetTable(entity.GetType()).InsertOnSubmit(entity);
}
else
{
Context.GetTable(entity.GetType()).Attach(entity, true);
}
foreach (PropertyInfo property in entity.GetType().GetProperties())
{
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntitySet<>))
{
IEnumerable children = (IEnumerable)property.GetValue(entity, null);
foreach (object child in children)
{
Save(child);
}
}
}
在我有一个子对象作为更新的一部分之前,这是有效的。例如,如果我传入一个Customer对象,该对象包含需要更新而不是插入的Address子对象,那么一旦我附加了Customer对象,我的EntitySet中就有两个Address对象—一个是从数据库中提取的,另一个是新的。然后,当它尝试附加第一个Address子对象时,我得到一个异常“cannotattachanentitywithexistings”。
有什么想法吗?