1、数据定义
Book表
using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;
using System.ComponentModel;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace EFTest.Models.Part2
{
[Table("Book")]
public class Book
{
[Key]
public int BookId { get; set;}
public string BookName { get; set; }
public int CatalogId { get; set; }
public virtual Catalog catalog { get; set; }
}
}
Catalog表
using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;
using System.ComponentModel;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace EFTest.Models.Part2
{
[Table("Catalog")]
public class Catalog
{
[Key]
public int CatalogId { get; set; }
public string Name { get; set; }
}
}
2.数据访问层
using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace EFTest.Models.Part2
{
public partial class DbContextFactory : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Catalog> Catalogs { get; set; }
}
}
web.config加入以下配置
<connectionStrings>
<add name="DbContextFactory"
providerName="System.Data.SqlClient"
connectionString="Server=(local);initial catalog=TestEF;user id=sa;password=abc123_;"/>
</connectionStrings>
数据增加、删除、修改
Book book = new Book
{
BookName = "kenny",
CatalogId = 3
};
using (var context = new DbContextFactory())
{
context.Books.Add(book);
context.SaveChanges();//增加
book = context.Books.Find(2);
context.Books.Remove(book);//删除
context.SaveChanges();
book = context.Books.Find(2);
book.BookName = "ss";
context.SaveChanges();//修改
}