I'm new in C# and trying to figure out the usage of entity framework and dependency injection in .Net console apps. The requirements for the app is to get the connection string from appsettings.json
. At the moment can't really figure out how should i pass connection options to AVLdbContext
.
Here is my AVLdbContext
class:
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();
}
}
And here is my Main
class where I'm creating the services and the path for AVLdbContext
and also trying to use 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["ConnectionStrings:DefaultConnection"]));
services.AddSingleton<IUnitOfWork, UnitOfWork>();
}).Build();
host.Run();
}
static void Main(string[] args)
{
Run();
var unitOfWork = new UnitOfWork(new AVLdbContext());
}
}
Here's my UnitOfWork
class.
public class UnitOfWork : IUnitOfWork
{
private readonly AVLdbContext _context;
public UnitOfWork(AVLdbContext context)
{
_context = context;
Devices = new DeviceRepository(_context);
}
//.........
This is the error i'm getting while trying to use UnitOfWork.
AVLdbContext
also have aconstructor
? – Aage Oct 21 at 9:56options
(of typeDbContextOptions<AVLdbContext>
) to theAVLdbContext
constructor – Rafalon Oct 21 at 10:02