zoukankan      html  css  js  c++  java
  • .NetCore之EF跳过的坑

    我在网上看到很多.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);
            }

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

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

  • 相关阅读:
    java 数据类型:集合接口Collection之List~ArrayList:remove移除;replaceAll改变原有值;sort排序;迭代器listIterator();
    java 数据类型:集合接口Collection之常用ArrayList;lambda表达式遍历;iterator遍历;forEachRemaining遍历;增强for遍历;removeIf批量操作集合元素(Predicate);
    java 常用类库:格式化NumberFormat;SimpleDataFormat类(转换Data()对象);DateTimeFormatter 转换LocalDateTime时间对象
    java 常用类库:时间类LocalDate;LocalTime;LocalDateTime;Calendar 类;Date ;
    java 常用类库:BigInteger大整数;BigDecimal大小数(解决double精度损失);
    java 常用类库:Math:常用min、max;floor;ceil;random;
    1345. Jump Game IV
    1298. Maximum Candies You Can Get from Boxes
    1293. Shortest Path in a Grid with Obstacles Elimination
    1263. Minimum Moves to Move a Box to Their Target Location
  • 原文地址:https://www.cnblogs.com/kq123321/p/6110078.html
Copyright © 2011-2022 走看看