linq2sql 更新数据问题
参考http://www.agiledon.com/post/Coding/LINQ-2-SQL-BaseClass.html
private void Detach(TEntity entity)
{
foreach (FieldInfo fi in entity.GetType().GetFields(BindingFlags.NonPublic |BindingFlags.Instance))
{
if (fi.FieldType.ToString().Contains("EntityRef"))
{
var value = fi.GetValue(entity);
if (value != null)
{
fi.SetValue(entity, null);
}
}
if (fi.FieldType.ToString().Contains("EntitySet"))
{
var value = fi.GetValue(entity);
if (value != null)
{
MethodInfo mi = value.GetType().GetMethod("Clear");
if (mi != null)
{
mi.Invoke(value, null);
}
fi.SetValue(entity, value);
}
}
}
}
{
foreach (FieldInfo fi in entity.GetType().GetFields(BindingFlags.NonPublic |BindingFlags.Instance))
{
if (fi.FieldType.ToString().Contains("EntityRef"))
{
var value = fi.GetValue(entity);
if (value != null)
{
fi.SetValue(entity, null);
}
}
if (fi.FieldType.ToString().Contains("EntitySet"))
{
var value = fi.GetValue(entity);
if (value != null)
{
MethodInfo mi = value.GetType().GetMethod("Clear");
if (mi != null)
{
mi.Invoke(value, null);
}
fi.SetValue(entity, value);
}
}
}
}
public void Update(TEntity originalEntity, Action<TEntity> update, bool hasRelationship)
{
InitDataContext();
try
{
if (hasRelationship)
{
//Remove the relationship between the entitis
Detach(originalEntity);
}
m_context.GetTable<TEntity>().Attach(originalEntity);
update(originalEntity);
m_context.SubmitChanges();
}
catch (ChangeConflictException)
{
m_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
m_context.SubmitChanges();
}
}