[英]Should I create in BLL project class the same like poco class in DAL project and return it to UI project if I want to display data from database?
我有一个架构问题。 我有带有Poco类的DAL项目(数据库中的等效表),BLL项目和UI项目。 UI项目引用了BLL项目,而BLL项目引用了DAL项目。
我想在UI项目数据中显示例如数据库表Product中的数据。 是否应该在BLL项目类中创建与DAL项目中的poco类相同的类,然后将其返回到UI项目并显示?
所以这是DAL中的我的poco类(数据库中的等效表):
public class Product
{
public int ID {get; set; }
public string Name {get; set; }
public String Address {get; set; }
}
在BLL中,我创建了与上面的poco类相同的业务对象:
public class ProductBO
{
public int ID { get; set; }
public string Name { get; set; }
public String Address { get; set; }
}
在BLL中,我还有一种从DAL获取产品并将其映射到业务对象的方法-ProductBO:
public class ProductService
{
public List<ProductBO> GetAllProducts()
{
List<ProductBO> productsBO = new List<ProductBO>();
using (var context = NorthwindFactory.CreateContext())
{
List<Product> products = context.Product.ToList();
foreach (var product in products)
{
productsBO.Add(new ProductBO { ID = product.ID, Address = product.Address, Name = product.Name });
}
}
return productsBO;
}
}
现在,在控制器的UI项目中,我从BLL调用服务,该服务返回List,并且在视图中可以使用业务对象ProductBO显示数据。
@model IEnumerable<WebApplication1.BLL.BusinessObjects.ProductBO>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
</tr>
}
</table>
它是正确的架构方法吗?
嗯,没有单一的正确方法 。 但是我倾向于避免创建DAL类集。 现代ORM允许与POCO类一起使用。 是的,有一些限制(例如枚举),但是恕我直言,它不值得为每个业务实体创建两个副本并在它们之间进行映射。 因此,我选择了位于业务逻辑组装中的单个POCO实体。 实体框架与该实体一起使用,可以从数据库中保存并加载它。 没有映射。
表示层不同。 通常,您在不同页面上具有相同实体的几种表示形式。 您还将使用不同的“数据注释”属性来设置对视图模型或某些UIHint的限制。 这将使用特定于UI的逻辑来污染您的业务实体。 同样,您经常需要显示格式化或修改后的数据,例如FullName,而不是Person实体的FirstName和LastName。 因此,这里我不使用我的POCO业务实体,而是创建视图模型。
对于您的产品样本,此方法将类似于:
Product
Product
ProductViewModel
, BriefProductViewModel
等。它还负责Product
和视图模型之间的映射。 注意-手动映射非常耗时。 我建议您使用一些映射库,例如AutoMapper或ValueInjecter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.