更新记录
转载请注明出处:
2022年10月12日 发布。
2022年10月9日 从笔记迁移到博客。
EF Core代码优先开发方式详解(Code First Development)
说明
记得先安装EF包,再使用
记得要给DbContext配置
默认构造函数
设置连接参数 否则不可以进行生成迁移
配置OnConfiguring方法
protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
代码优先开发模式的步骤
1.Create Database Context with connectionString
2.Create the model as a C# .Net class to generate a table.
3.Add public properties to the model with a data type and a name for fields.
4.Add the entity to the DBContext (if not already there) as DBSet
5.Generate a new code-first migration to apply any and all of the modeled changes using the add-migration command .
6.Update the database using the update-database command .
直接定义上下文对象DbContext方式
直接定义DbContext
using System;
using ConsoleApp6.Models;
using Microsoft.EntityFrameworkCore;
namespace ConsoleApp6.Repository
{
public class PandaDbContext: DbContext
{
/// <summary>
/// 选项配置器
/// </summary>
private DbContextOptionsBuilder _dbContextOptionsBuilder;
/// <summary>
/// 构造函数,支持外部配置项
/// </summary>
/// <param name="options">配置项</param>
public PandaDbContext(DbContextOptions options) :base(options)
{
}
/// <summary>
/// 默认构造函数
/// </summary>
public PandaDbContext() :base()
{
this._dbContextOptionsBuilder = new DbContextOptionsBuilder();
this._dbContextOptionsBuilder.UseSqlServer("Server=192.168.1.18;Database=PandaTest;User Id=sa;Password=password;");
}
/// <summary>
/// 配置上下文对象
/// </summary>
/// <param name="dbContextOptionsBuilder">选项配置器</param>
protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
{
if(!dbContextOptionsBuilder.IsConfigured)
{
dbContextOptionsBuilder.UseSqlServer("Server=192.168.1.18;Database=PandaTest;User Id=sa;Password=password;");
}
}
public DbSet<Product> Products { get; set; }
}
}
直接定义DbContext 带 配置类扩展
记得先安装配置类的扩展
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
并新建appsettings.json文件用于保存配置信息
{
"ConnectionStrings": {
"Panda": "Server=192.168.1.18;Database=PandaTest;User Id=sa;Password=password;"
}
}
Dbcontext代码:
using System;
using System.IO;
using ConsoleApp6.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp6.Repository
{
public class PandaDbContext: DbContext
{
/// <summary>
/// 选项配置器
/// </summary>
private DbContextOptionsBuilder _dbContextOptionsBuilder;
/// <summary>
/// 构造函数,支持外部配置项
/// </summary>
/// <param name="options">配置项</param>
public PandaDbContext(DbContextOptions options) :base(options)
{
}
/// <summary>
/// 默认构造函数
/// </summary>
public PandaDbContext() :base()
{
this._dbContextOptionsBuilder = new DbContextOptionsBuilder();
this._dbContextOptionsBuilder.UseSqlServer("Server=192.168.1.18;Database=PandaTest;User Id=sa;Password=password;");
}
/// <summary>
/// 配置上下文对象
/// </summary>
/// <param name="dbContextOptionsBuilder">选项配置器</param>
protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
{
if(!dbContextOptionsBuilder.IsConfigured)
{
//新建配置项生成器
ConfigurationBuilder builder = new ConfigurationBuilder();
//配置项生成器设置
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
//构建配置
var _configuration = builder.Build();
//获得配置的具体字符串
var cnstr = _configuration.GetConnectionString("Panda");
//使用连接字符串
dbContextOptionsBuilder.UseSqlServer(cnstr);
}
}
public DbSet<Product> Products { get; set; }
}
}
创建生成上下文DbContext对象的工厂类方式
using System;
using ConsoleApp6.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace ConsoleApp6
{
public class PandaDbContextFactory : IDesignTimeDbContextFactory<PandaDbContext>
{
public PandaDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<PandaDbContext>();
optionsBuilder.UseSqlServer("Server=192.168.1.198;Database=PandaTest;User Id=sa;Password=Password;");
return new PandaDbContext(optionsBuilder.Options);
}
}
}
EF代码优先开发方式详解(Code First Development)
概述
使用CodeFirst方式进行开发,则可以不使用.edmx文件进行描述数据结构
而是使用手动定义类文件的方式定义数据结构
开发人员创建DbContext类和DbSet类型的继承对象来进行处理数据
与使用实体对象模型开发的对比
Code First方式没法使用EF Designer设计工具
Code First方式中仅保留了实体对象模型开发中的DbContext和DbSet类型
使用Code First方式手动开发示例
在项目中添加EF Nuget包
安装EF包
项目中新建一个Models文件夹
在Models文件夹下添加一个Product.cs类文件并写入Product类
在Models文件夹下进行PandaModel.cs文件并写入内容
注意:引入命名空间System.Data.Entity
配置App.config文件中的连接字符串
注意:除了手动配置连接信息外,还可以使用VS -【工具】-【连接到数据库】
<connectionStrings>
<add name="pandaConnect" connectionString="data source=m1.panda666.com;initial catalog=PandaDatabase;persist security info=True;user id=sa;password=password;MultipleActiveResultSets=True;App=Entity Framework" providerName="System.Data.EntityClient"/>
</connectionStrings>
进行实际查询测试
using (PandaModel pandaModel = new PandaModel())
{
var queryResult = from item in pandaModel.products
select item;
foreach (Product item in queryResult)
{
Console.WriteLine("{0}-{1}-{2}",item.ProductId,item.ProductName,item.ProductType);
}
}
标签:Development,Code,dbContextOptionsBuilder,配置,DbContextOptionsBuilder,DbContext,开发
From: https://www.cnblogs.com/cqpanda/p/16771205.html