.net core 實現 data first的相關操作(一)

.net core 實現 data first的相關操作

先看一下demo目錄

一:準備操作:

1、先新建三個類:具有一對多的關係,添加了導航屬性(可以不加)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Data
{
    public enum Grade
    {
        A, B, C, D, F
    }
    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public Grade? Grade { get; set; }
        public Course Course { get; set; }
        public Student Student { get; set; }
    }
}

    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Data
{
    public class Student
    {
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Data
{
    public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }
    }
}

2、新建TestDbContext.cs(數據上下文)

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace WebApplication1.Data
{
    public class TestDbContext:DbContext
    {
        public TestDbContext(DbContextOptions<TestDbContext> options) : base(options)
        {

        }
        public DbSet<User> Uesrs { get; set; }
        public DbSet<Student> Student { get; set; }
        public DbSet<Enrollment> Enrollment { get; set; }
        public DbSet<Course> Course { get; set; }
    }
}

3、配置appsettings.json連接字符串(ConnectionStrings)

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "SqlServer": "Data Source=PC-20160722VLKH\\SQL2014;Initial Catalog=ZjTestDataBase;User Id=zhangjian;Password=123;"
  }
}

4、在startup.cs中添加如下代碼

----------------------------------------------

            var connection = Configuration.GetConnectionString("SqlServer");
            services.AddDbContext<TestDbContext>(options =>
                options.UseSqlServer(connection, b => b.MigrationsAssembly("WebApplication1")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

------------------------------------------------

  public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var connection = Configuration.GetConnectionString("SqlServer");
            services.AddDbContext<TestDbContext>(options =>
                options.UseSqlServer(connection, b => b.MigrationsAssembly("WebApplication1")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

5、右鍵你的web工程,編輯webapplication.csproj文件如下:

新增:Version爲EntityFrameworkCore的版本,可以去negut中查看

 <ItemGroup>
      <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.1.1" />
  </ItemGroup>

最終如下:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.1" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.1.1" />
  </ItemGroup>

</Project>

到這邊爲止,前期工作已經做完了,現在我們開始下一步:

二、生成到數據庫操作

1、主要是兩個命令:

dotnet ef migrations add v1   這個命令的作用的是:當我添加了類,就要改變v1成vn,相當於版本,這樣下面的命令才能知道實體被修改了,才能更新。如果實體修改了,這邊不修改,講不能更新。

注意點:要cd到項目的文件夾再執行,如圖所示:

 如果不報錯再執行下面的命令。

dotnet ef database update   這個命令的作用的是:把修改的更新到指定到數據庫。

注意點,不要使用sa,新建一個用戶,給與他創建數據庫的能力,如圖:

這樣就做完了。

最終效果圖如下:對比一下,這就是code first.

後面將繼續更新.net core學習,待續。。。有疑問聯繫我:qq:1057359832

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章