我是C#的新手,正在尝试弄清.Net控制台应用程序中实体框架和依赖项注入的用法。该应用程序的要求是从appsettings.json
获取连接字符串。目前无法真正弄清楚我应该如何将连接选项传递给AVLdbContext
。
这是我的AVLdbContext
课程:
public class AVLdbContext : DbContext
{
public AVLdbContext(DbContextOptions<AVLdbContext> options) : base(options){}
public DbSet<Package> Packages { get; set; }
public DbSet<Device> Devices { get; set; }
protected override void OnModelCreating (ModelBuilder modelBuilder)
{
modelBuilder.Entity<Package>()
.Property(p => p.Data)
.IsRequired();
modelBuilder.Entity<Device>()
.Property(b => b.Imei)
.IsRequired();
}
}
这是我的Main
类,我在其中创建服务和AVLdbContext
的路径,并尝试使用UnitOfWork
。
public class Program
{
public static IConfiguration Configuration { get; set; }
static void Run()
{
var host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
Configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
services.AddDbContext<AVLdbContext>(options =>
options.UseSqlite(Configuration["DefaultConnection"]));
services.AddSingleton<IUnitOfWork, UnitOfWork>();
}).Build();
host.Run();
}
static void Main(string[] args)
{
Run();
var unitOfWork = new UnitOfWork(new AVLdbContext());
}
}
这是我的UnitOfWork
课。
public class UnitOfWork : IUnitOfWork
{
private readonly AVLdbContext _context;
public UnitOfWork(AVLdbContext context)
{
_context = context;
Devices = new DeviceRepository(_context);
}
//.........
这是我尝试使用UnitOfWork时遇到的错误。 “>
非常感谢您的帮助。谢谢你的建议。
我是C#的新手,正在尝试弄清.Net控制台应用程序中实体框架和依赖项注入的用法。该应用程序的要求是从appsettings.json获取连接字符串。 ...
以下摘录来自Configuring a DbContext。