c# - 用于连接表的 MVC 核心存储库
问题描述
我们有带有多个带有外键的查找表的客户事务表。我们希望看到 3 个表连接在一起。存储库是否应该将表连接在一起,还是仅用于读取单个表?
如果是这样,示例存储库将数据放入什么?我听说它不知道 Viewmodels 等,那么结果会进入什么对象数据类型?
存储库:
void GetByCustomerTransactionId()
{
var result = from ct in CustomerTransaction
join pt in ProductType on pt.ProductTypeId equals ct.ProductTypeId
join ss in Status on s.StatusId equals ct.StatusId
select new all fields
}
楷模:
public class CustomerTransaction
{
public int CustomerTransactionId{ get; set; },
public int ProductTypeId {get; set; }, //joins to ProductTypeTable
public int StatusID {get; set; }, //joins to StatusTypeTable
public string DateOfPurchase{ get; set; },
public int PurchaseAmount { get; set; },
}
public class ProductType
{
public int ProductTypeId{ get; set; }
public string ProductName { get; set; },
public string ProductDescription { get; set; },
}
public class StatusType
{
public int StatusId{ get; set; }
public string StatusName{ get; set; },
public string Description{ get; set; },
}
解决方案
在 ASP.NET Core 中建立一对多关系的方法之一是Fluent API
public class CustomerTransaction
{
public int CustomerTransactionId { get; set; }
public string DateOfPurchase{ get; set; }
public int PurchaseAmount { get; set; }
// relationships
public ProductType ProductType { get; set; }
public int ProductTypeId { get; set; }
public StatusType StatusType { get; set; }
public int StatusID { get; set; }
}
public class ProductType
{
public int ProductTypeId { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
// relationships
public ICollection<CustomerTransaction> CustomerTransactions { get; set; }
}
public class StatusType
{
public int StatusId { get; set; }
public string StatusName { get; set; }
public string Description { get; set; }
// relationships
public ICollection<CustomerTransaction> CustomerTransactions { get; set; }
}
然后只需使用Include
将它们正确连接到您的结果中。
public void GetByCustomerTransactionId(int id)
{
var result = context.CustomerTransaction.Where(x=>x.CustomerTransactionId == id)
.Include(i=>i.ProductType)
.Include(i=>i.StatusType);
}
推荐阅读
- reactjs - 反应控制组件
- python - 我在使用漂亮的汤和 python 进行网络抓取时没有得到任何输出
- html - 当我更改页脚宽度时,文本一直向右移动
- python - Python多线程没有获得理想的性能
- javascript - React - 图像数组未正确渲染
- javascript - NODE.JS 错误:无法在视图目录中查找视图“/articles/[object Object]”
- prolog - Prolog for 8 谜题
- angular - 功能模块之间的Angular 9共享?
- python - 在 Python 和 PHP 之间发送 json
- c# - 如何检查变量是否被污染