Skip to main content
 首页 » 编程设计

c#之从多个表中选择,映射到 1 个对象

2024年02月06日15soundcode

假设我有 3 张 table

  1. 购买
  2. 销售
  3. 丢失库存

然后简化让我们定义这些类

public class Purchase { 
    public int Id {get;set;} 
    public int ProductId {get;set;} 
    public int PurchasedQ {get;set;} 
} 
public class Sales{ 
    public int Id {get;set;} 
    public int ProductId {get;set;} 
    public int SoldQ {get;set;} 
} 
public class LostInventory { 
    public int Id {get;set;} 
    public int ProductId {get;set;} 
    public int LostQ {get;set;} 
} 

时间过去了,我们的数据库中有 3 个购买对象、5 个销售对象和 2 个 LostInventory 对象。

现在我想让用户知道他的产品发生的历史。

为此,我正在考虑将这些对象映射到一个名为 historyItem 的新类

public class HistoryItem 
{ 
    public int Q {get; set;} 
    public int Type {get;set;} //specifies if the product history comed from a purchase, a sale or a lost 
    public int ItemId {get;set;} //specifies the id of the object in its table (according to Type) 
} 

我的想法可以吗?如果是这样,我怎么能做到这一点?我实际上找不到一个好的解决方案,这就是我正在尝试的

var targetProduct = 1; // an example target 
 
IQueryable<ProductHistory> purchasesQuery = db.purchases 
           .Where(x => x.ProductId == targetProduct) 
           .Select(x => new HistoryItem  
               { 
                    Q = x.PurchasedQ, 
                    Type = 1, 
                    ItemId = x.Id 
               }); 
 
IQueryable<ProductHistory> salesQuery = db.sales 
           .Where(x => x.ProductId == targetProduct) 
           .Select(x => new HistoryItem  
               { 
                    Q = -x.SoldQ, 
                    Type = 2, 
                    ItemId = x.Id 
               }); 
IQueryable<ProductHistory> lostQuery = ... 
 
//I need to return an Iqueryable containing them all 
return purchasesQuery + salesQuery + lostQuery //how to solve this?? 

我需要返回一个 IQueryable,因为它是 oData web api Controller 的一部分 谢谢。

请您参考如下方法:

怎么样

purchasesQuery.Concat(salesQuery.Concat(lostQuery)) 

或

purchasesQuery.Union(salesQuery.Union(lostQuery))