这次的Demo如标题所示,
首先第一步EF创建数据库
创建两个类,一个是图书类,一个是图书类别的类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication2.DAL
{
public class Book
{
[Key]
public int BookId {
get; set; }
public string BookName {
get; set; }
public string BookAuthor {
get; set; }
public virtual BookType TypeId {
get; set; }
public decimal Price {
get; set; }
public DateTime Addtime {
get; set; }
public string Img {
get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication2.DAL
{
public class BookType
{
[Key]
public int TypeId {
get; set; }
public string TyoeName {
get; set; }
}
}
添加一个ef创建数据库
这是EF自动生成的那个类,下面画横线的是需要自己写的,第一行是一个添加数据的类,稍后会在下面附上
namespace WebApplication2.DAL
{
using System;
using System.Data.Entity;
using System.Linq;
public class Model1 : DbContext
{
//您的上下文已配置为从您的应用程序的配置文件(App.config 或 Web.config)
//使用“Model1”连接字符串。默认情况下,此连接字符串针对您的 LocalDb 实例上的
//“WebApplication2.DAL.Model1”数据库。
//
//如果您想要针对其他数据库和/或数据库提供程序,请在应用程序配置文件中修改“Model1”
//连接字符串。
public Model1()
: base("name=Model1")
{
Database.SetInitializer(new InitDataBase());
}
public virtual DbSet<Book> Books {
get; set; }
public virtual DbSet<BookType> BookTypes {
get; set; }
//为您要在模型中包含的每种实体类型都添加 DbSet。有关配置和使用 Code First 模型
//的详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=390109。
// public virtual DbSet<MyEntity> MyEntities { get; set; }
}
//public class MyEntity
//{
// public int Id { get; set; }
// public string Name { get; set; }
//}
}
自动加载数据的类
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace WebApplication2.DAL
{
public class InitDataBase : DropCreateDatabaseIfModelChanges<Model1>
{
protected override void Seed(Model1 context)
{
BookType bookType1 = new BookType
{
TyoeName = "武侠"
};
BookType bookType4 = new BookType
{
TyoeName = "科幻"
}