2012-06-28 41 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; 
    }