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