新建类库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. python文件操作,读取,修改,合并

    # -*- coding:utf-8 -*- ''' 从11c开始提取 ''' import re import numpy as np import os year = '17A' ss=" ...

  2. 测试mktime和localtime_r性能及优化方法

    // 测试mktime和localtime_r性能及优化方法 // // 编译方法:g++ -g -o x x.cpp或g++ -O2 -o x x.cpp,两种编译方式性能基本相同. // // 结 ...

  3. (连通图 模板题 无向图求割点)Network --UVA--315(POJ--1144)

    链接: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  4. 作为CTO如何做技术升级

    升级技术架构,先要革新观念,最后才是技术问题 升级技术架构,不仅仅是技术升级 说到升级架构,大家第一个都会想到,是不是对技术升级一下就可以了? 我认为不是,技术架构升级要求的是整个公司的升级. 技术架 ...

  5. jpg/png格式图片转eps格式的方法--latex自带命令bmeps

    bmeps -h 命令查看bmeps的帮助信息 bmeps -c example.jpg example.eps

  6. dubbo在eclipse中无法读取到dubbo.xsd

    报错信息如下: Multiple annotations found at this line:– cvc-complex-type.2.4.c: The matching wildcard is s ...

  7. nginx优化笔记(keepalive、https等)

    一.nginx之tcp_nopush.tcp_nodelay.sendfile 1.TCP_NODELAY你怎么可以强制 socket 在它的缓冲区里发送数据?一个解决方案是 TCP 堆栈的 TCP_ ...

  8. HTML/HTML5

    HTML/HTML5 一.文档加载顺序. 文档入下,数字编号为加载顺序. <html><!--1--> <head><!--2--> <link ...

  9. vue-router页面传值及接收值

    主页  “去第二个页面”方法传值1 <template> <div id="app"> <div><router-link to=&quo ...

  10. 微信小程序支付C#后端源码

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...