新建类库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. 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...

  2. [.NET领域驱动设计实战系列]专题一:前期准备之EF CodeFirst

    一.前言 从去年已经接触领域驱动设计(Domain-Driven Design)了,当时就想自己搭建一个DDD框架,所以当时看了很多DDD方面的书,例如领域驱动模式与实战,领域驱动设计:软件核心复杂性 ...

  3. [转]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 ...

  4. EF CodeFirst 如何通过配置自动创建数据库<当模型改变时>

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    本篇为进阶篇,也是弥补自己之前没搞明白的地方,惭愧 ...

  5. EF CodeFirst增删改查之‘CRUD’

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    本篇旨在学习EF增删改查四大操作 上一节讲述了EF ...

  6. EF CodeFirst 创建数据库

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    话说EF支持三种模式:Code First   M ...

  7. 新年奉献MVC+EF(CodeFirst)+Easyui医药MIS系统

    本人闲来无事就把以前用Asp.net做过的一个医药管理信息系统用mvc,ef ,easyui重新做了一下,业务逻辑简化了许多,旨在加深对mvc,ef(codefirst),easyui,AutoMap ...

  8. EF Codefirst 初步学习(二)—— 程序管理命令 更新数据库

    前提:搭建成功codefirst相关代码,参见EF Codefirst  初步学习(一)--设置codefirst开发模式 具体需要注意点如下: 1.确保实体类库程序生成成功 2.确保实体表类库不缺少 ...

  9. EF CodeFirst系列(3)---EF中的继承策略(暂存)

    我们初始化数据库一节已经知道:EF为每一个具体的类生成了数据库的表.现在有了一个问题:我们在设计领域类时经常用到继承,这能让我们的代码更简洁且容易管理,在面向对象中有“has  a”和“is a”关系 ...

随机推荐

  1. HDU 2089 不要62 (递推+暴力或者数位DP)

    题意:中文题. 析:暴力先从1到1000000,然后输出就好了. 代码如下: #include <iostream> #include <cstdio> #include &l ...

  2. Hdu1548 A strange lift 2017-01-17 10:34 35人阅读 评论(0) 收藏

    A strange lift Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Tota ...

  3. 一致性哈希算法和Go语言实现

    一致性哈希算法,当我第一次听到这个名字的时候,感觉特别高深.而它往往会和分布式系统相关,准确的说,是分布式缓存. 在Web服务中,缓存是介于数据库和服务端程序之间的一个东西.在网站的业务还不是很大的时 ...

  4. spring MVC controller中的方法跳转到另外controller中的某个method的方法

    1. 需求背景     需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示. 本来以为挺简单的一 ...

  5. js正则处理千分位

    "222212345.098771".replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');

  6. C# npoi 从excel导入datagridviews 批量联网核查

    DataSet ds = new DataSet(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Fil ...

  7. 基于C#语言MVC框架Aspose.Cells控件导出Excel表数据

    控件bin文件下载地址:https://download.csdn.net/download/u012949335/10610726 @{ ViewBag.Title = "xx" ...

  8. C#穿透session隔离———Windows服务启动UI交互程序

    在Windows服务里面启动其他具有界面的应用程序,需要穿透session隔离,尝试了很多种方法,都可行,现在一一列举下来,并写下几个需要注意的地方. 需要注意的地方 首先要将服务的Account属性 ...

  9. disruptor调优方法

    翻译自disruptor在github上的文档,https://github.com/LMAX-Exchange/disruptor/wiki/Getting-Started Basic Tuning ...

  10. Day 7 深copy和浅Copy

    dict.fromkeys的用法 1 2 3 4 5 6 7 8 9 10 11 #dict.fromkeys的用法 #例子1 dic = dict.fromkeys([1,2,3],[]) prin ...