技术开发 频道

LINQ to SQL公共基类

删除方法是相似的,除了不需要调用Attach的第二个版本 (Attach(object entity, bool asModified))。代码片断如下:

public void Delete(TEntity entity, bool hasRelationship)
{
    InitDataContext();
    
try
    {
        
if (hasRelationship)
        {
            
//Remove the relationship between the entities;
            Detach(entity);
        }
        m_context.GetTable
<TEntity>().Attach(entity);
        m_context.GetTable
<TEntity>().DeleteOnSubmit(entity);
        m_context.SubmitChanges();
    }
    
catch (ChangeConflictException)
    {
        m_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
        m_context.SubmitChanges();
    }
}
public void Delete(IList<TEntity> entities, bool hasRelationship)
{
    InitDataContext();
    
try
    {
        
if (hasRelationship)
        {
            
//Remove the relationship
            foreach (TEntity entity in entities)
            {
                Detach(entity);
            }
        }
        m_context.GetTable
<TEntity>().AttachAll(entities);
        m_context.GetTable
<TEntity>().DeleteAllOnSubmit(entities);
        m_context.SubmitChanges();
    }
    
catch (ChangeConflictException)
    {
        m_context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
        m_context.SubmitChanges();
    }            
}
0
相关文章