我想创建一个 DDD 存储库,它返回与 Linq 到 SQL 基础类匹配的 IQueryable 实体,减去任何关系。我可以轻松地返回实体减去与 Linq 选择新 {field, field, ... } 投影的关系。如何编码存储库实体类?我将如何从具有存储库类而不是 Linq to SQL 类的存储库中返回一个对象,并且仍然使用来自 Linq 选择的多个实体填充它?我将如何在我的 ViewModel 中引用这个返回的类?
我对此很陌生,因此有明显的错误。我是否错过了这条船,应该只从存储库中返回完整的实体,而不是投影?在从存储库发送它们之前,我仍然需要去除 Linq 到 SQL 的关系。我完全不在基地吗?我真的很想保留 IQueryable 数据类型。
例如,我的存储库中的 Linq to SQL 代码:
public class MiniProduct
{
public MiniProduct( string ProductNo, string Name, string Description, double Price)
{ this.ProductNo = ProductNo;
this.Name = Name;
this.Description = Description;
this.Price = Price;
}
}
public IQueryable<MiniProduct> GetProductsByCategory( string productCategory)
{
return ( from p in db.Products
from c in db.Categories
from pc in db.ProductCategories
where c.CategoryName == productCategory &&
c.CatID == pc.CatID &&
pc.ProductID == p.ProductID
select new { p.ProductNo, p.Name, p.Description, p.Price } );
// how to return IQueryable<MiniProduct> instead of IQueryable<AnonymousType>???
}
在视图中(尝试强类型 ViewModel)我的模型数据类型是什么以及如何从视图中引用?
<% Page Inherits="System.Web.Mvc.ViewPage<MyStore.Models.MiniProduct>" %>
编辑:
Cottsak 授权代码并使其工作,因此他赢得了复选框。然而,Mark Seemann 指出,这种技术会产生副作用。他说得对,你的 POCO 是不好的。在使代码正常工作后,我最终制作了大量的一次性实体对象,这导致了不必要的复杂性。最终,我更改了代码以反映 Mark 的建议。
添加到 Cottsak 的建议:我的存储库返回值是 IQueryable。页面指令模型引用类型为
Inherits="System.Web.Mvc.ViewPage<IQueryable<MyStore.Models.MiniProduct>>"
模型字段由以下人员访问:
Model.SingleOrDefault().ProductNo
Model.SingleOrDefault().Name
...
这导致了一个
foreach (MyStore.Models.MiniProduct myproduct in Model) {}
谢谢两位的回答。