从多个表中选择,映射到一个对象



假设我有3个表

    购买
  1. 销售
  2. LostInventory

简化一下让我们定义这些类

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个purchase, 5个sales和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控制器的一部分谢谢。

purchasesQuery.Concat(salesQuery.Concat(lostQuery))

purchasesQuery.Union(salesQuery.Union(lostQuery))

相关内容

  • 没有找到相关文章