[英]Get (join) list where linked to optional List via Linq
I created my database via EF, and now (using LINQ) I want to return a list (called posts) where it is linked to its optional list (called flags) 我通过EF创建了我的数据库,现在(使用LINQ)我想返回一个列表(称为posts),它链接到它的可选列表(称为flags)
In the example below, you can see I give table Post a virtual List of flags (which means optional right?) 在下面的例子中,你可以看到我给表发布一个虚拟的标志列表(这意味着可选吗?)
MODEL : 型号:
public class Post
{
public int PostID { get; set; }
public string Title { get; set; }
public DateTime? Dateapproved { get; set; }
public virtual List<Flag> Flags { get; set; }
}
public class Flag
{
public int FlagID { get; set; }
public int PostID { get; set; }
}
EF : EF:
public class sampleProject : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Flag> Flags { get; set; }
}
How would I get a list of Posts where there is a link to flags, and Dateapproved is not null? 如何获得有标志链接的帖子列表,而Dateapproved不是空的?
Ofcourse this won't work, because the declaration is expecting a Post, and is getting a list of flags instead : 当然这不起作用,因为声明期待一个帖子,而是得到一个标志列表:
List<Post> postlist = context.Flags.Where(x => x.Post.DateApproved != null).ToList();
I know of the "Include" function, but not sure it will work here 我知道“包含”功能,但不确定它会在这里工作
What is the best practice here? 这里的最佳做法是什么? Should I split it somehow into more steps? 我应该以某种方式分成更多的步骤吗?
How would I get a list of Posts where there is a link to flags, and Dateapproved is not null? 如何获得有标志链接的帖子列表,而Dateapproved不是空的?
Try this: 尝试这个:
var posts = db.Posts.Include("Flags").Where(x => x.Flags.Any() && x.Dateapproved != null).ToList();
Use 采用
var result = from p in Posts
join f in Flags on p.PostId equals f.PostId
where f.Post.DateApproved != null
select p;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.