2012-06-28 44 views
2

在ASP.NET MVC3剃刀项目实体框架选择数据我有2种型号MVC,从多个模型

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列表绑定,但我不知道如何从两个模型中选择数据

回答

3

您可以创建一个视图模型这将只有性能其中U希望在视图中显示

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()); 
} 

,并创建一个类型的视图来呈现这种模式。

+0

感谢您的回答......其工作。 (必须将query.Single()更改为query.ToList()) – Nalaka526

+0

精彩。谢谢Pravin –

1

模型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(使用DIREKT视图)

您可以查看使用这样的:

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(通过控制器使用)-Recommended-

您可以使用控制器是这样的:

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

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

使用这种上查看

@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; 
    }