将自定义类型作为参数从PL传递到BLL到DAL到插入记录?

时间:2012-02-12 17:52:58

标签: c# entity-framework parameters crud

我在我的项目中使用Entity framworke。我使用3层架构(表示层(PL),业务逻辑层(BLL)和数据访问层(BAL))。实体框架定义所有实体以及BD的CRUD操作。

我遇到了一个基本问题。假设我需要在DB中插入客户。我想要 做如下

---------------PL-------------
Customer ObjCustomer=new Customer();

//init object
ObjCustomer.Name="";
--------------
------------

BLL.InsertCustomer(ObjCustomer)

------------------------------------------------

-------------------BLL---------------

DAL.InsertCustomer(ObjCustomer)

------------------------------------

-------------------DAL---------------

CustomerReporitory.InsertCustomer(ObjCustomer)

------------------------------------

现在的问题是,客户在DAL中定义为EF的一部分。不建议在PL中使用DAL ref。我想传递自定义类类型,如客户作为参数。怎么做。请给我一些示例代码。

2 个答案:

答案 0 :(得分:0)

表示层中的客户不应该是您的业务或数据层中的客户。表示层中的Customer应该类似于ViewModel,因此它应该只携带属性并在业务层中声明。这是应该为CreateCustomer发送到业务层的对象类型,CreateCustomer又从中创建业务实体或DAO并将其传递给持久性。

表示层

UserViewModel theUser=new UserViewModel(userNameField,passwordField);
userController.CreateUser(theUser);

业务层

public class UserController
{
    public void CreateUser(UserViewModel user)
    {
        bool isUserValid=ValidateUser(user);
        if(isUserValid)
        {
            UserEntity theEntity=new UserEntity(user);
            _userRepository.Create(theEntity);
        }
        else
        {
            throw new InvalidUserException("This user isn't valid");
        }
    }
}

数据层

public class UserRepository
{
    public void Create(UserEntity user)
    {
        /* store user to database or whatever */
    }
}

答案 1 :(得分:0)

如果您的模型没有方法或功能,并且只是一组get / set属性,您可以将它放在单独的程序集/命名空间中,并让所有层都将模型作为依赖项。这只是在非常简单的应用程序中推荐的,对于任何更复杂的应用程序都使用Tobias的方法。