我的商业逻辑应该去哪里?

时间:2011-02-16 20:57:55

标签: c# .net business-logic

我在我的应用程序中有以下逻辑分离,因为你可以看到我有一个名为SimpleController的类,这是我用来导入和查找SimpleEntities的。

我将所有SimpleEntities读入内存列表因为我经常搜索这些实体,并且每次我想搜索实体时从数据库中读取它的速度要快得多。

将我读取并将SimpleEntities存储到内存中的逻辑移到SimpleLogic类而不是SimpleController类中会不会更好?

public class SimpleEntity
{
    public int SimpleId { get; set; }
    public string SimpleName { get; set; }
}

public class SimpleDAL
{
    public ICollection<SimpleEntity> GetAllSimpleEntities()
    {
        //Retrieve SimpleEntities from Database
    }   
    public void InsertSimpleEntity(SimpleEntity simpleEntity)
    {
        //Insert simple Entity into Database
    }
}

public class SimpleLogic
{
    private readonly SimpleDAL simpleDAL = new SimpleDAL();

    public ICollection<SimpleEntity> GetAllSimpleEntities()
    {
        return simpleDAL.GetAllSimpleEntities();
    }
    public void InsertSimpleEntity(SimpleEntity simpleEntity)
    {
        //Validate simpleEntity before adding to database
        if (simpleEntity.SimpleId <= 0)
            throw new  Exception("Invalid SimpleEntity Id: " + simpleEntity.SimpleId);

        if (String.IsNullOrEmpty(simpleEntity.SimpleName))
            throw new Exception("SimpleEntity Name cannot be empty or null");

        simpleDAL.InsertSimpleEntity(simpleEntity);
    }
}

public class SimpleController
{
    private readonly SimpleLogic simpleLogic = new SimpleLogic();
    private List<SimpleEntity> simpleEntities;

    public SimpleController()
    {
        simpleEntities = simpleLogic.GetAllSimpleEntities().ToList();
    }

    public int FindSimpleIndex(int simpleId)
    {
        return simpleEntities.FindIndex(p=> p.SimpleId == simpleId);
    }

    public void ImportOtherSimpleEntity(OtherSimpleEntity otherSimpleEntity)
    {
        if (otherSimpleEntity.Operation == "Update")
        {
            int index = FindSimpleIndex(otherSimpleEntity.OtherSimpleId);
            //If entity was found update SimpleEntity
            if (index > -1)
            {
                //Call SimpleLogic.UpdateSimpleEntity(Pass in SimpleEntity);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我可能会实现一个SimpleEntityManager,它可以在控制器中引用,并且可以在必要时在其外部操作。因此,控制器处理系统的MVC方面,SimpleEntityManager管理SimpleEntities

另外,InsertSimpleEntity()似乎正在对SimpleEntity字段执行验证。我通常宁愿SimpleEntity执行验证本身(最有可能在构建期间)。