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, NameIf 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 开发者_Python百科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
}
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
精彩评论