entity framework core 2.0 & sqlite 配置教程
我用的是vs2017,需要下载.net core 2.0 sdk。
.net core 下载地址:点我下载
1.在Visual Studio之中创建一个.net core的控制台项目
2.修改csproj项目文件,注意添加 DotNetCliToolReference 节点,此节点为添加ef工具,不添加此节点无法使用dotnet ef系列命令
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /> </ItemGroup> <ItemGroup> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /> </ItemGroup> </Project>
3.这是我的Programs.cs文件,循环输入字符串添加到数据库表中
using System; using Microsoft.EntityFrameworkCore; using Microsoft.Data.Sqlite; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; namespace EfCore2Learn { class User { [Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { set; get; } [MaxLength(50), Required] public string Name { set; get; } } class MyContext : DbContext { public DbSet<User> Set_User { set; get; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string cntString = "Data Source=MyTestDb.db"; optionsBuilder.UseSqlite(cntString); } } class APP { public APP() { string inputStr = ""; inputStr = Console.ReadLine(); while (inputStr != "quit") { using (MyContext Db = new MyContext()) { User iUser = new User(); iUser.Name = inputStr; Db.Set_User.Add(iUser); Db.SaveChanges(); } inputStr = Console.ReadLine(); } } } class Program { static void Main(string[] args) { APP App = new APP(); } } }
4.在项目目录下打开cmd(我这里是PowerShell)分别输入以下命令
dotnet restore
dotnet dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet build
dotnet run
成功了,其实很简单,目前我配置好了SqlServer和Sqlite,但是MySql没有配置好,折腾了一天
这里是项目文件下载地址:点我下载项目文件