ITPub博客

首页 > 应用开发 > > .NetCore在运用EF出现错误

.NetCore在运用EF出现错误

作者:germo 时间:2019-08-21 11:38:28 0 删除 编辑

错误信息:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

构造的Context

public class DbContextHelper : DbContext
    {
        public DbSet<Student> StudentEntity { get; set; }

        public DbContextHelper() { }

        public DbContextHelper(DbContextOptions options) : base(options)
        {
        }

    }
接口和服务

 public interface IStudentService
    {
        Task<int> AddStudnet(Student entity);

        Task<int> DeltStudent(Guid id);

        List<Student> GetStudent(Expression<Func<Student,bool>> fun);
    }
public class StudentService : IStudentService
    {
        public  async Task<int> AddStudnet(Student entity)
        {
            using (DbContextHelper dbHelper =new DbContextHelper () ) {
                await dbHelper.AddAsync(entity);
                return dbHelper.SaveChanges();
            }
        }

        public async Task<int> DeltStudent(Guid id)
        {
            using (DbContextHelper dbHelper =new DbHelper.DbContextHelper ()) {
                var entity =await dbHelper.StudentEntity.FindAsync(id);
                if (entity == null)
                {
                    return -1;
                }
                else
                {
                    dbHelper.StudentEntity.Remove(entity);
                    return dbHelper.SaveChanges();
                }
            }
        }

        public List<Student> GetStudent(Expression<Func<Student, bool>> fun)
        {
            using (DbContextHelper dbHelper =new DbHelper.DbContextHelper ()) {
                var List = dbHelper.StudentEntity.Where(fun).ToList();
                return List;
            }
        }
    }
字符串链接配置

 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddDbContext<DbContextHelper>(options => options.UseSqlite(Configuration["AppSettings:DefaultConnectionStr"]));
            services.AddMvc();
            services.AddTransient<IStudentService, StudentService>();
        }
"AppSettings": {
    "DefaultConnectionStr": "data source=.; Initial Catalog=NetCore_TestDB ; uid=sa; pwd=qwertyuiop"
  }


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1868/viewspace-3122129/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-17

  • 博文量
    209
  • 访问量
    8229