新建类库Models,加入以下三个类:
Product:
public class Product { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } /// <summary> /// 型号 /// </summary> public string Code { get; set; } /// <summary> /// 单价 /// </summary> public double Price { get; set; } /// <summary> /// 单位 /// </summary> public string Unit { get; set; } /// <summary> /// 数量 /// </summary> public double Count { get; set; } /// <summary> /// 最后更新时间 /// </summary> public DateTime LastUpdateTime { get; set; } }
Purchase:
public class Purchase { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 产品编号 /// </summary> public int ProductId { get; set; } /// <summary> /// 单价 /// </summary> public double Price { get; set; } /// <summary> /// 数量 /// </summary> public double Count { get; set; } /// <summary> /// 总价 /// </summary> public double TotalPrice { get; set; } /// <summary> /// 实际总价 /// </summary> public double ActualPrice { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; } public virtual Product Product { get; set; } }
Sale:
public class Sale { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 产品编号 /// </summary> public int ProductId { get; set; } /// <summary> /// 单价 /// </summary> public double Price { get; set; } /// <summary> /// 数量 /// </summary> public double Count { get; set; } /// <summary> /// 总价 /// </summary> public double TotalPrice { get; set; } /// <summary> /// 实际总价 /// </summary> public double ActualPrice { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; } public virtual Product Product { get; set; } }
通过nuget引入EF:
install-package entityframework
在单元测试或者应用程序中也引入EF,在App.config或Web.config中会自动加入EF的配置:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="SalesDB" connectionString="server=.;database=SalesDB;uid=sa;pwd=pwd;" providerName="System.Data.SqlClient"/> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>
在connectionStrings节点中添加数据库连接
新建DBContext类:
public class SalesContext : DbContext { public SalesContext() : base("name=SalesDB") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<SalesContext, Models.Migrations.Configuration>("SalesDB")); } public DbSet<Product> Products { get; set; } public DbSet<Purchase> Purchases { get; set; } public DbSet<Sale> Sales { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } }
"name=SalesDB"表示使用config中配置的连接
Database.SetInitializer(new MigrateDatabaseToLatestVersion<SalesContext, Models.Migrations.Configuration>("SalesDB"));
开启自动迁移到最新版本,这样不会删除原有表和数据
在程序包管理控制台中输入:enable-migrations –EnableAutomaticMigration:$true,即可开启自动迁移。
当然也可以手动迁移,需要用到下面命令:
enable-migrations
会在Models中的Migrations目录中自动生成201603290414524_InitialCreate.cs
Add-migration
add-migration PurchaseChange 需要输入迁移的名称
会在Models中的Migrations目录中自动生成201603300705373_PurchaseChange.cs
Update-database
update-database –verbose可以看到迁移的代码
这里需要注意的是如果数据库中已有相同的表,再开启自动迁移的话会提示错误,这是只需把InitialCreate.cs删除再update-database即可
如果属性名为 Id 或 <类名>Id. Code-First 会自动以此创建主键.主键可以是任意类型, 如果主键是数字型或者GUID,会配置成自动增长或自动生成.
但如果像下面这样定义类的话就会报错:
public class Product {public int PId { get; set; } public string Name { get; set; } }
在Purchases类中,定义了Product的关联,
public int ProductId { get; set; } public virtual Product Product { get; set; }
EF会自动为在Purchases中创建ProductId 外键:
在迁移代码中可以看到:
public partial class PurchaseChange : DbMigration { public override void Up() { CreateIndex("dbo.Purchases", "ProductId"); AddForeignKey("dbo.Purchases", "ProductId", "dbo.Products", "Id", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.Purchases", "ProductId", "dbo.Products"); DropIndex("dbo.Purchases", new[] { "ProductId" }); } }
Sales类也添加了ProductId的外键,这样在创建Sale时如果新增Product的话,会自动把新增Product的Id赋值到Sale里的ProductId上:
using (var ctx = new SalesContext()) { Product p1 = new Product() { Name = "腐竹", Code = "002", Price = 3, Count = 100, Unit = "g", LastUpdateTime = DateTime.Now }; ctx.Products.Add(p1); Sale s1 = new Sale() { Price = 5, Count = 10, TotalPrice = 50, ActualPrice = 50, CreateTime = DateTime.Now,Product=p1 }; ctx.Sales.Add(s1); ctx.SaveChanges(); }
怎么进行多表查询呢?
public class Student { public Student() { } public int StudentID { get; set; } public string StudentName { get; set; } public DateTime? DateOfBirth { get; set; } public byte[] Photo { get; set; } public decimal Height { get; set; } public float Weight { get; set; } public int TeacherId { get; set; } public int StandardId { get; set; } }
public class Teacher { public Teacher() { } public int TeacherId { get; set; } public string TeacherName { get; set; } }
public class Standard { public Standard() { } public int StandardId { get; set; } public string StandardName { get; set; } }
这里没有定义表的外键,要查询的时候可以如下查询:
public class StudentViewModel { public int StudentID { get; set; } public string StudentName { get; set; } public string StandardName { get; set; } public string TeacherName { get; set; } }
var stu = from u in ctx.Students join da in ctx.Standards on u.StandardId equals da.StandardId join ta in ctx.Teachers on u.TeacherId equals ta.TeacherId select new StudentViewModel() { StudentID = u.StudentID, StudentName = u.StudentName, StandardName = da.StandardName, TeacherName = ta.TeacherName }; var stuview = stu.FirstOrDefault();