繁体   English   中英

MVC,实体框架从多个模型中选择数据

[英]MVC, Entity Framework Select data from multiple models

在ASP.NET MVC3 Razor项目中,我有2个模型

public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Contents { get; set; }
        public int Author { get; set; }
    }

 public class Author
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

Post.Author字段链接到Author.Id字段

在视图中,我需要显示列表

Post.Title
Post.Contents
Author.Name

如何显示(来自)两个模型的联接信息?

注意:我想我需要使用ViewModel并将视图与IEnumerable List绑定,但是我不知道如何从两个模型中选择数据

您可以创建一个视图模型,该模型仅具有您要在视图上显示的属性

public class PostViewModel
{
        public int Id { get; set; }
        public string Title { get; set; }
        public string Contents { get; set; }
        public string AuthorName { get; set; }

}

您需要在控制器操作中使用必要的联接在数据中填充此视图模型

public ActionResult GetAuthorInfor()
{
   var query = //context.Post join with context.Author
               Select new  PostViewModel()
               {
                  Id = post.id,
                  Title = post.title,
                  Contents = post.contents,
                  AuthorName = author.authorname
               }
   return view(query.Single());
}

并创建一个带类型的视图以呈现此模型。

模型Post.cs

public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Contents { get; set; }
        public int AuthorID { get; set; }

        public virtual Author Author { get; set; }
    }

模型Author.cs

public class Author
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
    }

DBContext类:

public class SampleDB : DbContext
    {
        public DbSet<Author> Authors{ get; set; }
        public DbSet<Post> Posts{ get; set; }
    }

I.Way(使用直接视图)

您可以像这样在View上使用:

 Samp.Models.SampleDB dbPosts = new Samp.Models.SampleDB();
 foreach (var post in dbPosts.Posts.ToList())
 {
   string post_Title = post.title;
   string post_Contents = post.Contents;
   string author_Name = post.Author.Name;
 }

II.Way(通过控制器使用)-推荐-

您可以像这样在Controller上使用:

Samp.Models.SampleDB db = new Samp.Models.SampleDB();

 public ActionResult Index()
 {
   return View(db.Posts.ToList());
 }

View上使用它:

@model IEnumerable<Samp.Models.Post>


foreach (var post in Model.Posts.ToList())
     {
       string post_Title = post.title;
       string post_Contents = post.Contents;
       string author_Name = post.Author.Name;
     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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