Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create a DbSet for 'Model' because this type is not included in the model for the context

I do a Generic and using DI

so I create a empty class

public class DBRepo
{ 
}

and my model class to inheriting class DBRepo

public partial class UserAccount : DBRepo
{
   public int Id { get; set; }
   public string Account { get; set; }
   public string Pwd { get; set; }
}

then this is a Interface to do CRUD

    public interface IDBAction<TEntity> where TEntity : class,new()
    {   
      void UpdateData(TEntity _entity);
      void GetAllData(TEntity _entity);
    }
public class DBService<TEntity> : IDBAction<TEntity> where TEntity : class,new()
{
    private readonly CoreContext _db;
    public DBService(CoreContext _db)
    {
        this._db = _db;
    }
    public void UpdateData(TEntity _entity)
    {
        this._db.Set<TEntity>().UpdateRange(_entity);
        this._db.SaveChanges();
    }
    public void GetAllData(TEntity _entity)
    {
        var x = this._db.Set<TEntity>().Select(o => o).ToList();
    }
}

And I Dependency Injection Service Provider in constructor

this.DBProvider = new ServiceCollection()
    .AddScoped<IDBAction<DBRepo>, DBService<DBRepo>>()
    .AddScoped<DBContext>()
    .AddDbContext<CoreContext>(options => options.UseSqlServer(ConnectionString))
    .BuildServiceProvider();

last step I Get Services

DBProvider.GetService<IDBAction<DBRepo>>().GetAllData(new UserAccount());

I will get a error message same with title

or I change to

DBProvider.GetService<IDBAction<UserAccount>>().GetAllData(new UserAccount());

I'll get other message

Object reference not set to an instance of an object.'

but the void UpdateData() is can work, so how to fix GetAllData() problem?

like image 373
鄭名宏 Avatar asked Mar 22 '18 09:03

鄭名宏


1 Answers

The error simply is because the class you're using here UserAccount has apparently not been added to your context, CoreContext. There should be a property there like:

public DbSet<UserAccount> UserAccounts { get; set; }

Regardless of whether you end up using the generic Set<T> accessor, you still must defined a DbSet for the entity on your context.

That said, you should absolutely not be creating your own service collection inside your repo. Register your context and your repo with the main service collection in Startup.cs and then simply inject your repo where you need it. The DI framework will take care of instantiating it with your context, as long as you have a constructor that takes your context (which you seem to).

And that said, you should ditch the repo entirely. It still requires a dependency on Entity Framework and doesn't do anything but proxy to Entity Framework methods. This is just an extra thing you have to maintain and test with no added benefit.

like image 85
Chris Pratt Avatar answered Oct 12 '22 19:10

Chris Pratt