.net core1.1 EF连接(Sql Server)数据库(类=>数据)

.net core1.1 EF连接(Sql Server)数据库(类=>数据)

测试环境

  • 系统 win10 x64
  • VSCode 1.12.1
  • .net core 1.1
  • .NET Command Line Tools (1.0.3)

操作

  1. 创建项目
  • dotnet new -o condoleEF
  1. 使用VSCode 打开, 输入下面的代码
  • consoleef.csproj 依赖程序集
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" PrivateAssets="All" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>
</Project>

  • blog.cs 数据库连接
using Microsoft.EntityFrameworkCore;

namespace consoleEF
{
    public class EFDbContext : DbContext
    {
        public virtual DbSet<Blog> Blogs { get; set; }
        // 数据库连接
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=.;Database=Blogging;Trusted_Connection=True;");
        }
    }

    public class Blog
    {
        public int Id{get; set;}
        public string Name{get; set;}
    }
}
  • Program.cs 测试连接
using System;
using consoleEF;

namespace consoleef
{
    class Program
    {
        static void Main(string[] args)
        {
            using(var db = new EFDbContext()){
                var blog = new Blog(){Name="Blog"};
                db.Blogs.Add(blog);
                db.SaveChanges();
            }
        }
    }
}

3.数据迁移

  • 注意如果在命令行终端下操作要再项目路径下进行
  • 数据迁移程序 dotnet ef migrations add db00

    《.net core1.1 EF连接(Sql Server)数据库(类=>数据)》” />    Paste_Image.png</li><li><p>生成数据库 dotnet ef database update</p><p> <img layer-src=     原文作者:YLPeach
        原文地址: https://www.jianshu.com/p/59d42995b422
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

点赞