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);
            }
        }
    }
}

 

 


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();
    }       
}

 

 

posted @ 2010-03-08 14:46  小白.net  阅读(311)  评论(0编辑  收藏  举报