无法为“模型”创建DbSet,因为此类型不包含在上下文的模型中

鄭名宏*_*鄭名宏 5 dependency-injection asp.net-core

我做一个泛型并使用DI

所以我创建一个空类

public class DBRepo
{ 
}
Run Code Online (Sandbox Code Playgroud)

和我的模型类继承类DBRepo

public partial class UserAccount : DBRepo
{
   public int Id { get; set; }
   public string Account { get; set; }
   public string Pwd { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

那么这是做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();
    }
}
Run Code Online (Sandbox Code Playgroud)

而我在构造函数中的依赖注入服务提供者

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

我获得服务的最后一步

DBProvider.GetService<IDBAction<DBRepo>>().GetAllData(new UserAccount());
Run Code Online (Sandbox Code Playgroud)

我将收到与标题相同的错误消息

或我改为

DBProvider.GetService<IDBAction<UserAccount>>().GetAllData(new UserAccount());
Run Code Online (Sandbox Code Playgroud)

我会收到其他消息

你调用的对象是空的。'

但是无效的UpdateData()是可以工作的,那么如何解决GetAllData()问题呢?

Chr*_*att 7

该错误只是因为您在此处使用的类UserAccount显然尚未添加到您的上下文中CoreContext。那里应该有一个属性,例如:

public DbSet<UserAccount> UserAccounts { get; set; }
Run Code Online (Sandbox Code Playgroud)

无论您最终是否使用通用Set<T>访问器,您仍然必须DbSet为上下文中的实体定义 a 。

也就是说,您绝对不应该在存储库中创建自己的服务集合。使用 Startup.cs 中的主服务集合注册您的上下文和存储库,然后只需在需要的地方注入您的存储库即可。只要您有一个接受您的上下文的构造函数(您似乎如此),DI 框架就会负责使用您的上下文实例化它。

也就是说您应该完全放弃该存储库。它仍然需要对实体框架的依赖,并且除了代理实体框架方法之外不执行任何操作。这只是您必须维护和测试的额外内容,没有额外的好处。