简体   繁体   中英

Entity Framework Include/select only certain properties from different tables

Let's say I have a method called GetThreadWithComments() . Each thread has 1 user (the creator) and has a list of comments. Each comments has 1 user (the poster).

Here are the classes (generated by EF):

public class Thread
{
    public int ThreadId { get; set; }
    public int UserId { get; set; }
    public string Message { get; set; }

    public List<Comment> Comments { get; set; }
    public User User { get; set; }
}

public class Comment
{
    public long CommentId { get; set; }
    public string Message { get; set; }
    public int UserId { get; set; }
    public int ThreadId { get; set; }

    public User User { get; set; }
}

So basically, I want to load a thread with user info, and associated comments with user info. I've tried something like this:

db.Threads.Select(x => new
{
    x,
    x.User = new { x.User.Username, x.User.Email },
    x.Comments = x.Comments.Select(c => new
    {
        c.Message,
        c.CommentId,
        c.User = new { c.User.Username, c.User.Email }
    })
});

The above does not work. However, I am not too sure on how to correctly do this. I could use include , but that would generate all properties. Since speed is a concern, I am trying to keep things as light as possible.

Reason it does not work: it does not build. Compile time error. The 2 errors I get are:

Cannot implicitly convert type '' to...

and

CS0746 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

First, define entity relationships as virtual , for example

public User User { get; set; }

should be

public virtual User User { get; set; }

Second, in case of the later posted compiler error, try adding the member names.

So instead of

x.User = new { x.User.Username, x.User.Email }

use

x.User = new { Username = x.User.Username, Email = x.User.Email }

Also there is too much x in there. The corrected example would be:

db.Threads.Select(x => new
{
    x,
    User = new { Username = x.User.Username, Email = x.User.Email },
    Comments = x.Comments.Select(c => new
    {
        c.Message,
        c.CommentId,
        User = new { Username = c.User.Username, Email = c.User.Email }
    })
});

Try this,

var result = db.Threads.Include(thread => thread.Comments);

Hope helps,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM