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();
        }

    }
}

最新文章

  1. A Xamarin.Forms Infinite Scrolling ListView
  2. 从Tmux 转到GNU Screen
  3. UDP网络通信OSC 协议
  4. robot API笔记2
  5. Python(2.7.6) 异常类的继承关系
  6. Android学习之路——简易版微信为例(二)
  7. 常用sql笔记
  8. C++笔试面试总结
  9. Gym 101102C Bored Judge(set--结构体集合)
  10. YII 数据库,模型,登录验证
  11. JDBC 程序实例小练习
  12. 极速创建 IOS APP !涛舅舅苹果 IOS APP自助生成系统!不用证书、不用越狱、永久可用
  13. 【亲测】502 Bad Gateway 怎么解决?
  14. Ubuntu设置静态IP的方法
  15. Java API下载和查阅方法
  16. android自定义风格的toast
  17. luoguP2572 [SCOI2010]序列操作
  18. iOS开发-NSPredicate
  19. Fundamental theorem of arithmetic 为什么1不是质数
  20. RabbitMQ的安装和配置化可视界面

热门文章

  1. iOS开发之Quartz2D 二:绘制直线,曲线,圆弧,矩形,椭圆,圆
  2. SDE 空间表操作
  3. 【z06】观光公交
  4. 如何使用Name对象,包括WorkspaceNames和DatasetNames
  5. linux网络编程学习笔记之二 -----错误异常处理和各种碎碎(更新中)
  6. java--css+js做的树形菜单(完整版)
  7. window.load和ready的差别
  8. JAVA SE回顾及思考(1)——面向对象的特点
  9. 一个自己犯的react错误
  10. js判断两个时间段是否有交集