2014-02-05 98 views
0

我有以下数据结构。 Data StructureLINQ EntityFramework,按属性排序

我想给查询方法的AttributeId,然后它应该由该AttributeId的价值排序List of vehicles

例如,如果两辆车都具有ID为123的属性并且车辆1具有值“cdf”并且车辆2具有值“abc”并且我将123传递给该方法,则其应该返回具有首先是车辆2,然后是车辆1。

整个查询方法正在工作,但我只是在努力与排序。如果任何人都能指出我的方向,那就太棒了!

这是基本的查询我现在所拥有的:

var query = (from v in context.Vehicles 
    //left join vehicleAttributes 
    join va in context.VehicleAttributes on v.VehicleId equals va.VehicleId into vAttributes 
    from vehicleAttributes in vAttributes.DefaultIfEmpty() 
    where v.FleetId == fleetId 
    select new { v, vehicleAttributes }); 

编辑: 我以前也说过这个,我当然通过vehicleAttributes.Value尝试了简单的订单,但由于每个车辆可以有多个vehicleattributes我不知何故需要通过我传递给查询的attributeId的值来指定查询。

+0

检查我的职务它会帮助你 – Developerzzz

+0

你想返回所有属性或只是与您传递到查询ID属性? – DavidN

回答

0
var query = (from v in context.Vehicles 

         //left join vehicleAttributes 
         join va in context.VehicleAttributes on v.VehicleId equals va.VehicleId into vAttributes 
         from vehicleAttributes in vAttributes.DefaultIfEmpty() 

         where v.FleetId == fleetId 
         orderby vehicleAttributes.Value ascending 
         select new { v, vehicleAttributes }); 
+0

这不起作用,因为车辆可以有多个车辆属性,我需要指定它应该通过attributeId的值来命令我传递给方法 – Timothy

0

你需要orderby

var query = (from v in context.Vehicles 
       join va in context.VehicleAttributes on v.VehicleId equals va.VehicleId 
       where v.FleetId == fleetId 
       orderby va.Value ascending 
       select new { Id = v.FleetId, Value = va.Value, Date = v.DateCreated }); 
0

很难理解如何这会工作,考虑到属性ID是主键,因此唯一的。不过,我认为这应该足以让你找到自己的方式。顺便说一句,你可以通过使用导航属性使你的查询更清洁。我定义了如下一个:

public class Vehicle 
    { 
     [Key] 
     public int VehicleId { get; set; } 

     public int FleetId { get; set; } 

     public virtual ICollection<VehicleAttribute> VehicleAttributes { get; set; } 
    } 


int fleetId = 1; 
int attributeId = 1; 
var q = from v in ctx.Vehicles 
    where v.FleetId == fleetId 
    select 
     new 
     { 
      v.VehicleId, 
      v.VehicleAttributes, 
      SortingAttribute = v.VehicleAttributes.FirstOrDefault(va => va.AttributeId == attributeId) 
     } 
    into output 
    orderby output.SortingAttribute.Value descending 
    select output;