1
votes

Goog Day!
Can anybody tell how to include sub-entity? I have the Forum project. The page, when I need to display all posts of topic, every post have Post informatin, User information, but, at that time, I need have information of User's group and User's role. (I can't attach image (low reputation), so I try to describe tables by words)
Post: id, Title, Text, UserId // Post.UserId = User.Id
User: id, Name, RoleId, GroupId // User.RoleId = RefRole.Id and User.GroupId = RefGroup.id
RefGroup: id, Name
RefRole: id, Name

If I include just User entity I do it like this:

    public ActionResult ViewTopic (int id)
    {
        ForumDBE forumDB = new ForumDBE();
        var posts = forumDB.Post.Include("User").ToList();
        return View(posts);
    }

But what need I to do, when at var post I need to have RoleName (for exapmple Administrator, Moderator, User) and Group Name (for example Good User, Best User, Advicer...) at View like this?

@model IEnumerable<MvcForum.Models.Post>

@foreach (var post in Model)
{
    User Name:  @post.User.Name
    User Group: @post.User.RefGroup.Name
    Uset Role:  @post.User.RefRole.Name
}
1
Have you tried .Include("User").Include("User.RefGroup").Include("User.RefRole"). From memory this works, but I am not 100%, so I'll comment rather than answer.Chris Sainty
in LINQ-to-SQL, once you got the model being with relations between Users table & RefGroups table for example, it automatically defines a new property in User named RefGroup. But in EF, I can't help.Ken D
I spent several days searching for an answer ... Thank you, very much! It works!! var posts = forumDB.Post.Include("User").Include("User.RefGroup").Include("User.RefRole").ToList();Chaki_Black

1 Answers

1
votes

In Entity Framework 4 default configuration you don't have to use Include

public ActionResult ViewTopic (int id)
    {
        ForumDBE forumDB = new ForumDBE();
        var posts = forumDB.Post; // or you can use .ToList() but I prefer to use IQueryable
        return View(posts);
    }

then

@model IQueryable<MvcForum.Models.Post>

@foreach (var post in Model)
{
    User Name:  @post.User.Name
    User Group: @post.User.RefGroup.Name
    Uset Role:  @post.User.RefRole.Name
}

It will use lazy loading since you are using IQueryable and not IEnumerable