EF CodeFirst Mirgration
新建类库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 = , Count = , Unit = "g", LastUpdateTime = DateTime.Now }; ctx.Products.Add(p1); Sale s1 = , Count = , TotalPrice = , ActualPrice = , 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();
EF CodeFirst Mirgration的更多相关文章
- 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...
- [.NET领域驱动设计实战系列]专题一:前期准备之EF CodeFirst
一.前言 从去年已经接触领域驱动设计(Domain-Driven Design)了,当时就想自己搭建一个DDD框架,所以当时看了很多DDD方面的书,例如领域驱动模式与实战,领域驱动设计:软件核心复杂性 ...
- [转]Using Entity Framework (EF) Code-First Migrations in nopCommerce for Fast Customizations
本文转自:https://www.pronopcommerce.com/using-entity-framework-ef-code-first-migrations-in-nopcommerce-f ...
- EF CodeFirst 如何通过配置自动创建数据库<当模型改变时>
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 本篇为进阶篇,也是弥补自己之前没搞明白的地方,惭愧 ...
- EF CodeFirst增删改查之‘CRUD’
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 本篇旨在学习EF增删改查四大操作 上一节讲述了EF ...
- EF CodeFirst 创建数据库
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 话说EF支持三种模式:Code First M ...
- 新年奉献MVC+EF(CodeFirst)+Easyui医药MIS系统
本人闲来无事就把以前用Asp.net做过的一个医药管理信息系统用mvc,ef ,easyui重新做了一下,业务逻辑简化了许多,旨在加深对mvc,ef(codefirst),easyui,AutoMap ...
- EF Codefirst 初步学习(二)—— 程序管理命令 更新数据库
前提:搭建成功codefirst相关代码,参见EF Codefirst 初步学习(一)--设置codefirst开发模式 具体需要注意点如下: 1.确保实体类库程序生成成功 2.确保实体表类库不缺少 ...
- EF CodeFirst系列(3)---EF中的继承策略(暂存)
我们初始化数据库一节已经知道:EF为每一个具体的类生成了数据库的表.现在有了一个问题:我们在设计领域类时经常用到继承,这能让我们的代码更简洁且容易管理,在面向对象中有“has a”和“is a”关系 ...
随机推荐
- Ubuntu在命令行开启远程桌面
在终端执行下列三个命令即可 gsettings set org.gnome.Vino enabled truegsettings set org.gnome.Vino prompt-enabled f ...
- Airplace平台
Demo: 左上角:(0, 0)开始导航,手机终端上实时在地图上当前所在显示,当前点以绿色点显示,轨迹点以红色显示. 系统架构:基于移动手机的以网络为辅助的架构.特点:低头顶交流,用户隐私和安全 &g ...
- 20155339 2016-2017-2 《Java程序设计》第9周学习总结
20155339 2016-2017-2 <Java程序设计>第9周学习总结 教材学习内容总结 JDBC入门 JDBC简介 JDBC全名Java DataBase Connectivity ...
- NoSQL: Cassandra, HBase, RocksDB
转自: http://www.linkedin.com/pulse/nosql-cassandra-hbase-rocksdb-siddharth-anand I've had the pleasur ...
- webupload编辑回显解决方案
webupload java参考:http://blog.csdn.net/finalAmativeness/article/details/54668090 回显参考: https://segmen ...
- shell 脚本,将/etc/目录下所有的软链接文件输出
#!/bin/bash # cd /etc for a in *;do if [ -L $a ];then #如果文件存在,为软链接文件且指向的是文件,则返回真 echo $a fi done 测试:
- POJ1410_还是没考虑全面——线段是否与矩形有共同的垂直投影
题意如题目 有几个点1.怪我没读好题目:给出的矩形两个端点不一定都是左上右下,但是肯定能勾勒出一个矩形. 2.现在才发现很多线段相交的判断我都没有仔细考虑这一个问题 bool ssinsert(Poi ...
- 获得硬盘的ID序列号(XE10.1+WIN8.1)
疯狂delphi DelphiXE公开课群:100162924.58593121 朱建强QQ:513187410 获得硬盘的ID序列号(XE10.1+WIN8.1) 相关资料: https://zhi ...
- Windows / Windows Phone 8.1 预留应用名称及应用上传
最近比较懒好久没有来这里跟大家聊了,WP 8.1 的 preview 发布已经有一阵子了,并且商店支持 8.1 应用也有一段时间了.我就把这篇 8.1 的应用商店预留提交作为 8.1 的一个开始吧. ...
- [LeetCode 题解] Spiral Matrix
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 题目链接 54. Spiral Matrix ...