广州商城网站建设地址,大企业网站样式,网站内容维护,网站建设的出路测试环境#xff1a; 
visual studio 2017 
.net core 2.1  具体步骤如下#xff1a; 
1 新增名称为EFCoreDemo的.net core控制台程序#xff0c;版本选择.net core 2.1#xff0c;项目不能放到带中文的目录下#xff0c;不然到后面执行Add-Migration命令时会报如下的错误…测试环境 
visual studio 2017 
.net core 2.1  具体步骤如下 
1 新增名称为EFCoreDemo的.net core控制台程序版本选择.net core 2.1项目不能放到带中文的目录下不然到后面执行Add-Migration命令时会报如下的错误 同时如果这个解决方案有多个项目一定要把当前项目设为启动项目且程序包管理器控制台默认项目一定要选对不然到后面执行Add-Migration命令时会报如下的错误 2  利用Nuget安装Microsoft.EntityFrameworkCore.Sqlite版本选择2.2.6及安装Microsoft.EntityFrameworkCore.Tools版本选择2.2.6如下图 
(注意安装Microsoft.EntityFrameworkCore.Sqlite时会把EF Core对应的依赖包Microsoft.EntityFrameworkCore等都自动安装上不用再单独安装   如果数据库是Sql Server则安装Microsoft.EntityFrameworkCore.SqlServer) 3  新增实体类Student并编辑如下 
using System;
using System.Collections.Generic;
using System.Text;namespace EFCoreDemo
{public class Student{public long Id { set; get; }public string Name { set; get; }}
}4  新增Student类对应的配置类StudentConfig并编辑如下 
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;namespace EFCoreDemo
{public class StudentConfig : IEntityTypeConfigurationStudent{public void Configure(EntityTypeBuilderStudent builder){builder.ToTable(Student);}}
}5  新增上下文类MyDbContext并编辑如下 
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;namespace EFCoreDemo
{public class MyDbContext:DbContext{public DbSetStudent Students { set; get; }protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){base.OnConfiguring(optionsBuilder);optionsBuilder.UseSqlite(Data SourceKnowledgeDataBase.sqlite;);}protected override void OnModelCreating(ModelBuilder modelBuilder){base.OnModelCreating(modelBuilder);modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);}}
}上面的的KnowledgeDataBase.sqlite为SqLite的数据库文件名称 6  打开程序包管理控制台     
6.1  输入命令Add-Migration Init如下图 然后会在项目中自动生成目录Migrations并自动3个类不要动它们如下图 6.2  输入命令Update-database会执行更新如下图 由于用的是SqLite数据库会在项目中生成一个名为 KnowledgeDataBase.sqlite的数据库文件并设置为始终复制如下图 7  主程序编辑如下 
using System;
using System.Linq;namespace EFCoreDemo
{class Program{static void Main(string[] args){Student stu  new Student();stu.Name  zxy;MyDbContext myDbContext  new MyDbContext();myDbContext.Add(stu);myDbContext.SaveChanges();var studentsmyDbContext.Students.Where(a  a.Name  zxy);foreach (var item in students){Console.WriteLine($Id:{item.Id} Name:{item.Name});}Console.WriteLine(执行完毕);Console.ReadLine();}}
}运行结果如下 好了本文的内容到此结束