I have below class structure,
public partial class Class1 : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[StringLength(500)]
public string Description { get; set; }
public virtual ICollection<Class2> Class2s { get; set; }
}
public partial class Class2 : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[StringLength(500)]
public string Description { get; set; }
[Required]
[ForeignKey("Class1")]
public Guid Class1_Id { get; set; }
public virtual Class1 Class1 { get; set; }
}
public class BaseEntity
{
public BaseEntity()
{
Meta = new MetaData();
}
public MetaData Meta { get; set; }
}
public sealed class MetaData
{
public bool Active { get; set; }
public DateTimeOffset Created { get; set; }
public DateTimeOffset? Modified { get; set; }
public MetaData()
{
Created = DateTime.UtcNow;
Active = true;
}
}
Now using EF,
var dbContext.Class1
.Include(x=>x.Class2)
where (x=>x.Meta.Active)
Now I want to load/filter/get all active class2 entities using above query.
I have tried to apply filter on .Include(x=>x.Class2).Where(y=>y.Meta.Active)
but it apply only on Class1. I want to filter all active class2 entities.
Please help. Thanks in Advance.
To filter navigation property collection you can use method Query . It looks like this:
context.Entry(blog)
.Collection(b => b.Posts)
.Query()
.Where(p => p.Tags.Contains("entity-framework")
.Load();
Or you can do the following:
dbContext.Class1
.Select(s => new {class1 = s, navigationProps = s.Class2s.Where(w => w.Meta.Active)})
.AsEnumerable()
.Select(s => s.class1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.