Register generic EntityFrameworkCore DbContext in ASP.Net Core 1.0

asp.net-core-1.0 asp.net-mvc c# entity-framework-core generics

Question

I am trying to use generic DbContext in ASP.Net Core 1.0 however I am getting following error:

ArgumentException: Type 'idmin.data.IdminDataContext`1[System.Int32]' does not have a default constructor Parameter name: type 

Here is how IdminDataContext is defined:

public class IdminDataContext<TKey> : DbContext where TKey : IEquatable<TKey>
{

    public IdminDataContext(DbContextOptions<IdminDataContext<TKey>> options) : base(options)
    {
    }

    public DbSet<Idmin.Models.Client<TKey>> Clients { get; set; }
}

and here is how I am registering it in startup class.

public void ConfigureServices(IServiceCollection services)
{
    var connection = "my connection string";
    services.AddDbContext<IdminDataContext<int>>(options => options.UseSqlServer(connection));

    services.AddMvc();
}

I tried adding default constructor in IdminDataContext class but it didn't help. Any idea what am I missing here?

1
2
7/17/2016 5:27:35 PM

Accepted Answer

I found issue. It was silly mistake on my part. Instead of using constructor injection in Controller I was using action method injection which was causing exception in Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder's CreateModel method. Fixed this issue by moving dependency injection to constructor instead of action method injection.

3
7/18/2016 12:00:06 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow