0

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)

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 :

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?

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?

4

2 回答 2

2

How would I get a list of Posts where there is a link to flags, and Dateapproved is not null?

Try this:

var posts = db.Posts.Include("Flags").Where(x => x.Flags.Any() && x.Dateapproved != null).ToList();
于 2012-11-23T13:11:44.507 回答
0

Use

  var result = from p in Posts
               join f in Flags on p.PostId equals f.PostId
               where f.Post.DateApproved != null
               select p;
于 2012-11-23T13:01:35.057 回答