首页 > 解决方案 > 用于连接表的 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; },

}

标签: c#asp.net-mvcasp.net-core

解决方案


在 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);
}

推荐阅读