标签:
首先创建一个Model类
public class Book
{
public int id { get; set; }
public string BookName { get; set; }
public string Writer { get; set; }
public decimal Price { get; set; }
public DateTime Time { get; set; }
public int Amount { get; set; }
public virtual BookType bookTypes { get; set; }
创建BookType
public class BookType
{
public int id { get; set; }
public string Booktype { get; set; }
public ICollection<Book> books { get; set; }
}
创建数据文上下类
public class BookContext2:DbContext
{
public DbSet<Book> books { get; set; }
public DbSet<BookType> booktypes { get; set; }
}
同志!!!!!!!记得修改web.config里面的数据库链接
创建控制器,选择读写模板,选择book类,上下文类
private BookContext2 db = new BookContext2();
public ActionResult Index()
{
return View(db.books.ToList());
}
public ActionResult Details(int id = 0)
{
Book book = db.books.Find(id);
if (book == null)
{
return HttpNotFound();
}
return View(book);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
创建视图
@model IEnumerable<_2.Models.Book>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
@foreach(var item in Model){
<li>
@Html.ActionLink(@item.BookName, "Details", new { id=@item.id})
</li>
}
</ul>
标签:
原文地址:http://www.cnblogs.com/shenbinlei/p/5100301.html