我创建了从类 IdentityDbContext 继承的类 DataContect:
using ProjDAL.Entities;
using ProjDAL.Relations;
using ProjDAL.Services;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
namespace ProjDAL.EF
{
public class DataContext : IdentityDbContext<ApplicationUser>
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
.......................................................
}
解决方案具有控制台应用程序,可在其中创建新的数据上下文:
using System;
using DbInitialize.Interface;
using ProjDAL.EF;
namespace DbInitialize.Provider
{
public class DbInitializeProvider : IDbInitialize
{
private DataContext _db;
public DbInitializeProvider()
{
_db = new DataContext(options => options.UseSqlServer("Data Source=.\SQLEXPRESS;Initial Catalog=ProjAppTest;Integrated Security=True;MultipleActiveResultSets=true"));
}
public void SetCreateDatabase()
{
Console.WriteLine("Check for database availability: ");
using (var transaction = _db.Database.BeginTransaction())
{
try {
if(_db.Database != null)
{
Console.WriteLine("Done!rn");
}
else
{
_db.Database.EnsureCreated();
Console.WriteLine("Database was created!rn");
}
transaction.Commit();
}
catch (DbException error)
{
Console.WriteLine(error);
transaction.Rollback();
}
}
}
}
}
我的程序.cs文件:
using System;
using DbInitialize.Provider;
using ProjDAL.EF;
namespace DbInitialize
{
class Program
{
private static readonly DbInitializeProvider _db;
delegate void Display();
static Program()
{
_db = new DbInitializeProvider();
}
static void Main(string[] args)
{
try
{
Display display = _db.SetCreateDatabase;
display.Invoke();
Console.WriteLine($"rn{new string('-', 80)}");
Console.WriteLine("For continue press any button...");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
我收到错误:
无法将 lambda 表达式转换为类型"
DbContextOptions <DataContext>
",因为它不是委托类型
如何正确创建数据上下文实例并设置选项参数?
如果您需要更多信息,请告诉我。谢谢你的帮助。
创建 DataContext
类时,参数与您在 DataContext
构造函数中定义的内容不匹配。它需要一个类型为 DbContextOptions<DataContext>
的对象,但您正在为操作提供选项参数options => options.UseSqlServer("Data Source=.\SQLEXPRESS;Initial Catalog=ProjAppTest;Integrated Security=True;MultipleActiveResultSets=true")
您需要构建选项对象并将实例提供给构造函数:
var optionsBuilder = new DbContextOptionsBuilder<DataContext>();
optionsBuilder.UseSqlServer("YOUR CONNECTION STRING");
_db = new DataContext(optionsBuilder.Options)
或者,您可以使用不带参数的构造函数,并在 OnConfiguring
方法的 DataContext
类中对其进行配置。
请参阅此处的文档:https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext