实现一个包含多个更新方法的类的最佳实践是什么,意图重复代码较少?

时间:2015-08-29 11:27:08

标签: c# entity-framework

让我说我有以下方法

public class Class1
{
        public void UpdateMethod1()
        {
            Entities.StaticDataEntities entities=new StaticDataEntities();
            //insert some items or make some changes in entity
            entities.SaveChanges();
        }
        public void UpdateMethod2()
        {
            Entities.StaticDataEntities entities=new StaticDataEntities();
            //insert some items or make some changes in entity
            entities.SaveChanges();
        }
        ....
}

实现这样一个示例的最佳方法是什么,该示例包含几个具有更新责任的方法?我的目的是从我的代码中删除额外的entities.SaveChanges();Entities.StaticDataEntities entities=new StaticDataEntities();,并将其带到包装类或类似的东西。顺便说一句,如果问题标题不适合帮助改变它。

1 个答案:

答案 0 :(得分:1)

您可以尝试这样做:

public class Class1
{
    public void UpdateMethod1()
    {
        UpdateWrapper(entities => {
            //insert some items or make some changes in entity
        }); 
    }
    public void UpdateMethod2()
    {
        UpdateWrapper(entities => {
            //insert some items or make some changes in entity
        });                       
    }

    private static void UpdateWrapper(Action<StaticDataEntities> update)
    {
        var entities = new StaticDataEntities();
        update(entities);
        entities.SaveChanges();
    }
}

<强>更新

  

这很好,但我还是需要在每个方法中使用updatewrapper方法,有没有其他方法可以将savechanges方法放在另一个类和层中并调用该层?

最简单的方法是将UpdateWrapper从类中带到帮助器并将其重构为:

public static class UpdateHelper
{
    // where ObjectContext is the base class for 'StaticDataEntities' that contains ObjectContext.SaveChanges();
    public static int Update<T>(Action<T> action) where T : ObjectContext, new()
    {
        var entities = new T();
        action(entities);
        return entities.SaveChanges();
    }
}

同样Class1也应该重构:

public class Class1
{
    public void UpdateMethod1(StaticDataEntities entities)
    {            
        //insert some items or make some changes in entity
    }
    public void UpdateMethod2(StaticDataEntities entities)
    {            
        //insert some items or make some changes in entity
    }        
}

然后你可以这样使用它:

var x = new Class1();
UpdateHelper.Update<StaticDataEntities>(x.UpdateMethod1); // via a method group
UpdateHelper.Update<StaticDataEntities>(o => x.UpdateMethod2(o)); // via classic lambda