技术开发 频道

LINQ to SQL公共基类

{
            
if (hasRelationship)
            {
                
//Remove the relationship between the entitis
                Detach(originalEntity);
            }

            m_context.GetTable
<TEntity>().Attach(originalEntity);

            update(originalEntity);

            SubmitChanges(m_context);
      }
      
catch (InvalidCastException ex)
      {
          LogService.Error(
"Update Entity error.", ex);
          
return false;
      }
      
catch (NotSupportedException ex)
      {
          LogService.Error(
"Update Entity error.", ex);
          
return false;
      }
      
catch (Exception ex)
      {
          LogService.Error(
"Update Entity error.", ex);
          
return false;
      }    
    }
}

    
现在,我们拥有了一个通用的公共类,实体对象的访问类可以继承它。例如:

public class EmployeeAccessor:AccessorBase<Employee,NorthwindDataContext>
{
}


你不需要实现任何方法,就能够很方便地对实体对象进行操作:
[TestMethod()]

public void UpdateEmployee()
{
    EmployeeAccessor accessor
= new EmployeeAccessor();
    IList
<Employee> entities = accessor.Where(e => e.EmployeeID == 1);
    
if (entities != null && entities.Count > 0)
    {
        entities[
0].FirstName = "Bruce";
        entities[
0].LastName = "Zhang";

        accessor.Update(entities[
0],true,true);
    }
}


你甚至可以直接让Employee实体类继承基类:

public partial class Employee:AccessorBase<Employee,NorthwindDataContext>
{
}


这种方法类似于充血模式,正如Martin Fowler在Anemic Domain Model一文中提到的那样。

源代码下载:Download Source - 126kb
 

0
相关文章