我们有Customer事务表,其中包含多个带外键的查找表。我们希望看到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; },
}
答案 0 :(得分:0)
考虑到表上存在外键约束,您只需执行此操作而无需自己进行任何连接
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; },
// Add this
public ProductType ProductType { get; set;}
public StatusType StatusType { get; set;}
}
然后在您的存储库上只需获取CustomerTransation,它也将根据其外键返回已连接的表
CustomerTransaction GetByCustomerTransactionId(int id)
{
var result = ct.CustomerTransaction.Where(x => x.CustomerTransactionId == id).ToList()
return result;
}
这将为您提供CustomerTransactions,其StatusType和ProductType
答案 1 :(得分:0)
在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);
}