• EF Code First 快速创建


    以.net framework为例,包括数据库管理类库和启动项目两个项目文件

    数据库管理类库

    新建一个类库,名称为XXX.Database
    管理nuget包,引入库EntityFramework 6.2.0
    创建表

    public class Student
    {
    	[Key]
    	public int Id { get; set; }
    	public string Name { get; set; }
    }
    

    创建DbContext,设置nameOrConnectionString为"YourDatabase"

    public class YourDbContext: DbContext
    {
    	public DbSet<Student> Students { get; set; }
    
    	public YourDbContext(): base("YourDatabase")
    	{
    
    	}
    }
    

    启动项目

    这里启动项为一个控制台程序,同样添加EntityFramework 6.2.0
    在App.config文件中添加连接字符串,注意,名称为"YourDatabase"
    这里是Sql Server数据库的连接字符串

    <configuration>
      <connectionStrings>
        <add name="YourDatabase" providerName="System.Data.SqlClient" connectionString="Data Source=YourIp;Initial Catalog=XXXDb;User Id=userId;Password=password;"/>
      </connectionStrings>
    </configuration>
    

    其中providerName的名称,和App.config中的provider对应,后者是引入EntityFramework的时候自动添加的
    至此,两个项目均可识别EntityFramework,添加了数据库上下文、数据库表、连接字符串,可以开始迁库

    迁库

    打开包管理控制台(Package Manager Console),设置默认程序(Default project)为XXX.Database,启动项为上述的控制台程序
    首先,允许迁库

    Enable-Migrations
    

    会自动生成Migrations文件夹及相关文件
    然后创建迁移文件

    add-migration add_Student_table
    

    执行更新

    update-database
    

    使用

    查询

    using (var dbContext = new YourDbContext())
    {
    	var s = dbContext.Students.FirstOrDefault(x => x.Id == 1);
    }
    

    其他不再赘述

    参考资料

    Entity Framework 5.0 Code First全面学习

  • 相关阅读:
    C++三大特性之多态
    内向者沟通圣经:4P法(Preparation,Presence,Push,Practice)
    RTP/RTCP、TCP、UDP、RTMP、RTSP
    网络七层协议
    预防U盘被病毒侵害的方法
    Win8安装程序出现2502、2503错误解决方法
    小L的区间求和
    【剑指offer-12】矩阵中的路径
    【剑指offer】数值的整数次方
    【剑指offer】二进制中1的个数
  • 原文地址:https://www.cnblogs.com/Lulus/p/11142881.html
Copyright © 2020-2023  润新知