实现网上书店的例子

选择基本模版

1.创建模型类Book

 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; }//外键一对多
    }

2.创建模型类BookType

 public class BookType
    {
        public int id { get; set; }
        public string Booktype { get; set; }

        public ICollection<Book> books { get; set; }//外键一对多

    }

3.创建数据库上下文

public class BookContext2:DbContext
    {
        public DbSet<Book> books { get; set; }
        public DbSet<BookType> booktypes { get; set; }
    }

4.数据迁移:视图->其它窗口->程序包管理器

enable-

add-

update-

Webcofig中更改connectionstring与数据库上下文名字相同

5.创建控制器

强类型视图->模型类->数据库上下文类

 public class HomeController : Controller
    {
        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);
        }
    }

6.创建视图Index

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

创建视图Detail

选择强类型,Detail模板

 

posted @ 2016-01-05 09:58  butterfly小d  阅读(255)  评论(0编辑  收藏  举报