2017-10-12 79 views
0

我有以下的(简化)设置:C#LINQ到实体包括与条件和订购

Public class parent 
{ 
    public string name{get;set;} 

    public list<child> childList {get;set;} 
} 


Public class child 
{ 
    public int id {get;set;} 

    public bool imported{get;set;} 

    public dateTime? timeSpan {get;set;} 
} 

,我有这个疑问:

var relevant = context.parent 
       .include(x => x.child.OrderByDescending(y => y.id).FirstOrDefaultAsync(z => z.imported == false && timeSpan == null) 
       .Where(x => x.child != null); 

不工作。

基本上,我想包括所有的父母孩子,但为了他们的ID下降,然后检查是否第一个(例如最新的一个)具有imported == falsetimeSpan == null,并且只包括有一个孩子的父行是符合这个条件。

我知道我可以做到这一点:

var relevant = context.parent 
       .include(x => x.child); 

,然后提取我需要的数据,但有可能使用LINQ做一个?

+0

也许相关https://stackoverflow.com/questions/32751427/conditional-include-in-entity-framework – OmG

回答

1

正如你使用的标签linq-to-entities我假设你正在使用实体框架。

在我看来,你已经模仿父母与子女之间的一个一对多的关系:每一位家长都有零个或多个孩子,而每个孩子都属于一个母公司。

这也可能是因为你有很多一对多的关系。该班略有不同(和数据库将有你不要在您的DbContext有一个额外的表),但问题依旧。

这可能是因为你的简化,但我看到你的类中的某些奇怪的事情,可能会导致您的问题。

public class Parent 
{ 
    public int Id {get;set;} 
    public string name{get;set;} 

    // Every parent has zero or more Children 
    public virtual ICollection<Child> Children {get;set;} 
} 

public class Child 
{ 
    public int id {get;set;} 
    public bool Imported{get;set;} 
    public DateTime? TimeSpan {get;set;} 

    // every Child belongs to exactly one Parent using foreign key 
    public int ParentId {get; set;} 
    public Parent Parent {get; set;} 
} 

儿童的父集合不能是一个列表:

在实体框架如下适当的一个一对多的关系进行建模。 ChildList [3]意味着什么?

此外,该系列应该是虚拟的(见SO: Understanding code first virtual properties

您写道:

基本上,我想包括所有的父母孩子,但为了 他们的ID下降,然后检查如果第一个(例如最新的一个) 先后引进== false,并且时间跨度== null,而只包括具有满足该条件的孩子 父行。

有点难以理解,但似乎你有父母的序列,并且希望只有那些父母和他们的孩子,其中最高childID的孩子是不是进口的,并有一个空时间跨度。

var result = dbContext.Parents 
    .Select(parent => new 
    { 
     // Take all Parent properties you need in your end result, for example 
     Id = parent.Id, 
     Name = parent.Name, 
     Children = parent.Children 
      .OrderByDescending(child => child.Id), 
    }) 
    .Select(parent => new 
    { 
     Id = parent.Id, 
     Name = parent.Name, 
     Children = parent.Childrent, 
     NewestChild = parent.Children.FirstOrDefault(), 
    }) 
    // keep only the parents you want to keep: 
    .Where(parent => parent.NewestChild != null 
     && !parent.NewestChild.Imported 
     && parent.NewestChild.TimeSpan == null));