【问题标题】:Passing custom type as parameter from PL to BLL to DAL to Insert record?将自定义类型作为参数从 PL 传递到 BLL 到 DAL 以插入记录?
【发布时间】:2012-03-04 07:12:51
【问题描述】:

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

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

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

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

BLL.InsertCustomer(ObjCustomer)

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

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

DAL.InsertCustomer(ObjCustomer)

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

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

CustomerReporitory.InsertCustomer(ObjCustomer)

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

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

【问题讨论】:

  • 客户有什么方法还是只是一堆属性?

标签: c# entity-framework parameters crud


【解决方案1】:

您的表示层中的客户不应是您的业务或数据层中的客户。表示层中的 Customer 应该类似于 ViewModel,因此它应该只携带属性并在业务层中声明。这是应为 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 */
    }
}

【讨论】:

  • 如果客户实体在 BLL 中定义,它将可以从 PL 访问,但不能从 DAL 访问。所以从 BLL 到 DAL 我必须将所有客户属性作为单独的参数传递?你能告诉我示例代码吗>
  • 在 BLL 中你需要根据你的业务规则从 ViewModel 创建一个实体并将它传递给 DAL 进行持久化,是的。
  • 通常我们在 BLL 中引用 DAL 但不反向。那么,如果我在 BLL 中定义实体,它将如何在 DAL 中访问?
  • 这是常规 3 层架构的缺点之一;实体必须在 DAL 中定义,否则您必须使用在 DAL 中定义的数据访问对象,该对象是您从实体构造的。
  • 非常感谢您的解释/示例代码。现在我只对这一行感到困惑 [UserEntity theEntity=new UserEntity(user);]。如何从 [UserViewModel] 类型创建 UserEntity 或者您的意思是说从 PL 传递的 [user] 对象传递构造 UserEntity 的对象,最后将其传递给持久层。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2013-05-31
    • 2020-08-31
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多