Entity Framework Include/select only certain properties from different tables

c# dbcontext entity-framework entity-framework-core

Question

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.

1
2
2/13/2018 7:24:20 AM

Accepted Answer

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 }
    })
});
1
2/13/2018 7:04:25 AM

Popular Answer

Try this,

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

Hope helps,



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow