2011-03-24 118 views
0

這裏是我用我的項目查詢之一:如何在select子句中創建匿名類型列表?



var carQuery = from cars in context.Cars 
          .Where(c => c.CarID==3) 
          from stockTypes in context.StockTypes 
          .Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty() 
          from carUnit in context.Car_Units 
          .Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty() 
          from carAttributes in context.Car_Attributes 
          .Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty() 
          from attribute in context.Attributes 
          .Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty() 

          select new 
          { 
           CarID = cars.CarID, 
           CarName = cars.CarName, 
           CarDescription = cars.CarDescription, 
           StockType = (stockTypes == null) ? null : new 
           { 
            StockTypeID = stockTypes.StockTypeID, 
            StockName = stockTypes.StockName 
           }, 
           IsActive = cars.IsActive, 
           IsCab = cars.IsCab, 
           Unit = (carUnit == null) ? null : new 
           { 
            Id = carUnit.UnitId, 
            Name = carUnit.Unit.UnitName 
           }, 
           Attributes = attribute 
          }; 

如果context.Attributes返回多行,整個結果集返回也多行。

有沒有可能將具有多個屬性的單一車型作爲屬性列表返回給汽車?

請幫忙。

感謝, 馬赫什

回答

0

你只需要移動結果集裏面的屬性查詢:

 var carQuery = from cars in context.Cars 
         .Where(c => c.CarID==3) 
         from stockTypes in context.StockTypes 
         .Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty() 
         from carUnit in context.Car_Units 
         .Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty() 
         from carAttributes in context.Car_Attributes 
         .Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty() 

         select new 
         { 
          CarID = cars.CarID, 
          CarName = cars.CarName, 
          CarDescription = cars.CarDescription, 
          StockType = (stockTypes == null) ? null : new 
          { 
           StockTypeID = stockTypes.StockTypeID, 
           StockName = stockTypes.StockName 
          }, 
          IsActive = cars.IsActive, 
          IsCab = cars.IsCab, 
          Unit = (carUnit == null) ? null : new 
          { 
           Id = carUnit.UnitId, 
           Name = carUnit.Unit.UnitName 
          }, 
          Attributes = 
           from attribute in context.Attributes 
           .Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty() 
           .GroupBy(at => at.AttributeId) 
           select attribute 
         }; 
+0

是不是你的屬性行缺少一個選擇? – Hogan 2011-03-24 17:52:24

+0

@霍根:哎呀。謝謝! – Gabe 2011-03-24 17:53:37