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

时间:2015-06-06 00:02:42

标签: c# linq entity-framework

假设我有3张桌子

  1. 购买
  2. 销售
  3. LostInventory
  4. 简化让我们定义这些类

    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控制器的一部分 感谢。

1 个答案:

答案 0 :(得分:4)

怎么样

purchasesQuery.Concat(salesQuery.Concat(lostQuery))

purchasesQuery.Union(salesQuery.Union(lostQuery))