.net Core

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

2017-05-08  本文已影响28人  YLPeach

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


测试环境


操作

  1. 创建项目
  1. 使用VSCode 打开, 输入下面的代码
<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>

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;}
    }
}
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.数据迁移

!! VSCode 这个版本的

上一篇下一篇

猜你喜欢

热点阅读