我有以下数据结构。
我想给查询方法AttributeId
,然后应该按List of vehicles
的值对AttributeId
进行排序。
例如,如果两辆车都具有id为123的属性且vehicle1具有值“cdf”且vehicle2具有值“abc”并且我将123传递给该方法,则它应返回车辆列表2首先,然后是车辆。
整个查询方法正在运行,但我只是在努力排序。如果有人能指出我正确的方向那将是伟大的!
这是我现在的基本查询:
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 :(得分: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 });
答案 1 :(得分: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 });
答案 2 :(得分:0)
考虑到AttributeId是主键并因此是唯一的,很难理解这是如何工作的。但是,我认为这应该足以让你找到自己的方式。顺便说一句,您可以使用导航属性使您的查询更清晰。我定义了以下一个:
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;