我在网上看到很多.netCore的信息,就动手自己写一个例子测试哈,但是想不到其中这么多坑;

1.首先.netCore和EF的安装就不用多说了,网上有很多的讲解可以跟着一步一步的下载和安装,但是需要注意点就安装Microsoft.EntityFrameworkCore.SqlServer程序包(Install-Package Microsoft.EntityFrameworkCore.Sqlite –Pre)

2.创建实体

/// <summary>
    ///  学生类
    /// </summary>
    public class Student
    {
        /// <summary>
        /// ID
        /// </summary>
        [Key]
        public Guid ID { get; set; } = Guid.NewGuid();
        /// <summary>
        /// 名字
        /// </summary>
        [StringLength(50)]
        [Required]
        public string Name { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public EmSex Sex { get; set; } = EmSex.未填;
    }
    public enum EmSex
    {
        男 = 0,
        女 = 1,
        未填 = 2
    }

3.创建EF的上下文DbContext

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

        public DbContextHelper() { }

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

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    string str = "data source=.; Initial Catalog=NetCore_TestDB ; uid=sa; pwd=qwertyuiop";
        //    optionsBuilder.UseSqlServer(str);
        //    //optionsBuilder.UseSqlite(str);
         
        //}
    }

4.编写数据库操作的接口和实现类

 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;
            }
        }
    }
View Code

5.创建Controller进行调用

public class HomeController : Controller
    {
        private IStudentService StudentDb = new StudentService();
        // GET: /<controller>/
        public IActionResult Index()
        {
            var  list = StudentDb.GetStudent(it=>true);
            return View();
        }
    }

6.下面配置数据库链接和EF的初始化创建

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            //services.AddEntityFrameworkSqlServer()
            //    .AddDbContext<DbContextHelper>();
            //options =>
           // options.UseSqlServer(Configuration["AppSettings:DefaultConnectionStr"])
            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"
  },

上面很多网上都有相关的资料可以查询,我这里只是梳理了哈,下面开始运行

开始报这个错误

后面经过查看很多资料,晓得是上下文的注册造成的,这个问题就需要注意几点:

1.获取字符串一定要注意不要不能包含空格符号

services.AddDbContext<DbContextHelper>(options => options.UseSqlite(Configuration["AppSettings:DefaultConnectionStr"]));

2.一定给要注意区分哈UseSqlite和UseSqlServer;

修改之后运行,还是会有上面的问题,具体原因我也不是很清楚,但是我找宁外一种解决方案进行初始化数据库链接字符串,重写OnConfiguring

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string str = "data source=.; Initial Catalog=NetCore_TestDB ; uid=sa; pwd=qwertyuiop";
            optionsBuilder.UseSqlServer(str);
        }

修改之后在运行,问题得到了解决。

需要源码留下邮箱我看到后发,一起讨论!