MVC EF Code First

1 在Models里面创建类,用[Key]特性指定主键;

2 在Model里面增加导航属性;

3 在web.config里面增加连接字符串

4 创建继承于DbContext的类

5 创建Controller类,生成Index视图

6 在Controller类的Index()里面,通过context.Database.CreateIfNotExist()


//BookInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;




namespace CodeFirst.Models
{
    public class BookInfo
    {
        [Key]
        public int BookId { get; set; }
        public string BookTitle { get; set; }
        public int TypeId { get; set; }


        public BookType BookType { get; set; }
    }

}


//BookType.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;


namespace CodeFirst.Models
{
    public class BookType
    {
         [Key]
        public int TypeId { get; set; }
        public string TypeTitle { get; set; }
        public ICollection<BookInfo> BookInfo { get; set; }
    }

}

//BooksContext

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;


namespace CodeFirst.Models
{
    public class BooksContext:DbContext
    {
        public BooksContext():base("name=BooksContext")
        {
            
        }


        DbSet<BookInfo> BookInfo { get; set; }


        DbSet<BookType> BookType { get; set; }
    }

}


//web.config

 <connectionStrings>
    <add name="BooksContext" connectionString="server=.;database=books;uid=sa;pwd=Server2012" providerName="System.Data.SqlClient"/>

  </connectionStrings>

//BooksController

using CodeFirst.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace CodeFirst.Controllers
{
    public class BooksController : Controller
    {


        DbContext context = new BooksContext();
            
        //
        // GET: /Books/


        public ActionResult Index()
        {
            context.Database.CreateIfNotExists();
            context.SaveChanges();

            return View();
        }


    }
}

posted @ 2018-04-26 17:21  dxm809  阅读(77)  评论(0编辑  收藏  举报