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

假如想象 提交于 2021-01-27 04:51:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/49425348/cannot-create-a-dbset-for-model-because-this-type-is-not-included-in-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!