选择具有多个关系的实体

时间:2016-12-14 20:42:04

标签: c# asp.net-mvc entity-framework

我有以下实体:

车辆

public class Vehicle
{
    [Key]
    public int ID { get; set; }
    public int CurrentOdometer { get; set; }
    ....
    public VehicleModel VehicleModel { get; set; }
    public ICollection<PerformedService> PerformedServices { get; set; }
}

VehicleModel

public class VehicleModel
{
    [Key]
    public int ID { get; set; }
    ....
    public ICollection<Vehicle> Vehicles { get; set; }
    public ICollection<ServiceInterval> ServiceIntervals { get; set; }
}

ServiceIntervals

 public class ServiceInterval
{
    [Key]
    public int ID { get; set; }
    ....
    [Required]
    [Display(Name="Kilometer Interval")]
    public int KmInterval { get; set; }

    public VehicleModel VehicleModel { get; set; }

    public ICollection<ServiceSheet> ServiceSheets { get; set; }

}

ServiceSheets

[Key]
    public int ID { get; set; }
    .....
    public ServiceInterval ServiceInterval { get; set; }
    public ICollection<ServiceSheetQuestions> ServiceSheetQuestions { get; set; }

    public ICollection<PerformedService> PerformedServices { get; set; }

}

PerformedServices

 public class PerformedService
{
    [Key]
    public int ID { get; set; }

    [Display(Name = "Vehicle Serviced")]
    public virtual Vehicle Vehicle { get; set; }

    [Display(Name = "Service Comments")]
    public string Comments { get; set; }

    public ServiceSheet ServiceSheet { get; set; }
    public WeeklyService WeeklyService { get; set; }

    public ICollection<VehicleAction> VehicleActions { get; set; }
    public ICollection<VehicleIssue> VehicleIssues { get; set; }
    public ICollection<ServiceSheetAnswer> ServiceSheetAnswers { get; set; }
    public ICollection<WeeklyServiceAnswer> WeeklyServiceAnswers { get; set; }

}

我面临的问题是,我需要车辆模型中的下一张服务单,其中没有来自车辆的执行服务且服务间隔是>然后车辆电流表。

我正在尝试使用此查询:

 var teste = vehicle.VehicleModel.ServiceIntervals.FirstOrDefault(x => x.KmInterval > vehicle.CurrentOdometer && x.ServiceSheets.Where(b => b.PerformedServices.Intersect(vehicle.PerformedServices).Any()) == null);
 ServiceSheet serviceSheets = vehicle.VehicleModel.ServiceIntervals.FirstOrDefault(x => x.KmInterval > vehicle.CurrentOdometer && x.ServiceSheets.Where(b => !b.PerformedServices.Intersect(vehicle.PerformedServices).Any()) == null).ServiceSheets.Where(x => !x.PerformedServices.Intersect(vehicle.PerformedServices).Any()).FirstOrDefault();

但我没有成功。

1 个答案:

答案 0 :(得分:0)

我非常喜欢使用LINQ查询查询数据库的能力,只要您监控EF发送给您的数据库服务器的查询,我认为它既方便,又易读且快速。

在您的情况下,查询很复杂,在我看来,人们在获取LINQ查询意图方面遇到困难的可能性非常高。

这是回退到普通旧SQL的非常有效的情况。好消息是Entity Framework supports it并且仍然负责将结果绑定到您的域类。结果将更容易理解 - 特别是有这么多JOIN - 你知道EF不会自己创建一个怪物查询。