模型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;
}
感謝您的回答......其工作。 (必須將query.Single()更改爲query.ToList()) – Nalaka526
精彩。謝謝Pravin –