获取由linq

时间:2018-05-15 10:01:29

标签: entity-framework linq

我有3个实体:SurveysBatchRemoved,其中Surveys是父表,另外两个与使用外键的Surveys相关。

public class Surveys
{
    public int TireID { get; set; }
    public dateTime DateCreated{ get; set; }
}
public class Batch
{
    public int TireID { get; set; }
    public int TirePosition{ get; set; }
    public ICollection<Surveys> Survey{ get; set; }
}
public class Removed
{
    public int TireID { get; set; }
    public int TirePosition{ get; set; }
    public dateTime DateRemoved{ get; set; }
    public ICollection<Surveys> Survey{ get; set; }
}

我有一个查询来获取构成调查的一部分的轮胎批次,以及已删除的轮胎:

var surveys = ctx.Surveys.Where(a => a.DateSubmitted >= startDate && a.DateSubmitted < endDate).Select(a => new T_Batch
{
    //don't know how to get desired result
}).ToList();

我有一个自定义类型,查询结果(T_Batch)应该是:

public class T_Batch
{
    public int TireID { get; set; }
    public int TirePosition { get; 
    public T_Removed Removed{ get; set; }
}
public class T_Removed
{
    public int TireID { get; set; }
    public int TirePosition { get; set; }
}

查询结果带回了调查列表,这很好,但是我希望每个轮胎列表项目的轮胎列表,以及每个轮胎位置移除的轮胎(如果有一个被移除)。我不知道如何实现这一点。

期望结果的示例:

    0 Batch_Tire1
    1 Batch_Tire2
        0 Removed_Tire
    2 Batch_Tire3
    3 Batch_Tire4
        0 Removed_Tire
 etc...

更新

我可以做这样的事情,但我需要将结果集作为我的自定义类型。

var surveys = ctx.TM_Survey.Where(a => a.DateSubmitted >= startDate && a.DateSubmitted < endDate).Select(a => new
{
    BatchItem = a.Batch,
    RemovedItem = a.Removed
}).ToList();

更新2

或者我可以这样做,但结果只返回有限数量的行,等于TM_Survey

中的键数
var surveys = ctx.TM_Survey.Where(a => a.DateSubmitted >= startDate && a.DateSubmitted < endDate).Select(a => new T_Batch
{
    TireID = a.T_Batch.Select(b => b.ID).First(),
    TirePosition = a.T_Batch.Select(b => b.TirePosition).First()
    Removed = new T_Removed 
    { 
      //...etc 
    }
}).ToList();

0 个答案:

没有答案