• 002 Entity Framework Core 2.x P2 表关系 一对多 多对多


    002 Entity Framework Core 2.x P2 表关系 一对多 多对多


    博客园文章Id:12700088


    项目结构

    项目结构
    项目结构

    AspEFCore.Data

    需要引用的依赖项如下:

    Microsoft.EntityFramework.Core.Tools

    Microsoft.EntityFramework.Core.Design

    编写EF上下文类:

    using AspEFCore.DoMain.Models;
    using Microsoft.EntityFrameworkCore;
    
    namespace AspEFCore.Data
    {
        public class MyContext : DbContext
        {
            /*
             * Ef Core 需要 DbContextOptions 类型的配置才能进行工作,所以此处的配置,我们需要在Startup类中进行注入,
             * 才能使用此DbContext.
             */
            public MyContext(DbContextOptions<MyContext> options) : base(options)
            {
    
            }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<City>()
                    .HasOne(x => x.Province)   //指向外键表的导航属性
                    .WithMany(x => x.Cities)   //外键表的导航属性指向自己
                    .HasForeignKey(x=>x.ProvinceId);             //外键表Id
    
                modelBuilder.Entity<CityCompany>()
                    .HasKey(x => new {x.CityId, x.CompanyId});         //创建联合主键
    
                modelBuilder.Entity<CityCompany>()               
                    .HasOne(x => x.City)             //指向外键表的导航属性
                    .WithMany(x => x.CityCompanies)  //外键表的导航属性指向自己
                    .HasForeignKey(x => x.CityId);                     //外键表Id
    
                modelBuilder.Entity<CityCompany>()
                    .HasOne(x => x.Company)         //指向外键表的导航属性
                    .WithMany(x => x.CityCompanies) //外键表的导航属性指向自己
                    .HasForeignKey(x => x.CompanyId);                 //外键表Id
    
                modelBuilder.Entity<Mayor>()
                    .HasOne(x => x.City)             //指向外键表的导航属性
                    .WithOne(x=>x.Mayor)             //外键表的导航属性指向自己
                    .HasForeignKey<Mayor>(x => x.CityId);             //外键表Id
    
            }
    
            public DbSet<Province> Province { get; set; }
            public DbSet<City> City { get; set; }
            public DbSet<CityCompany> CityCompany { get; set; }
            public DbSet<Mayor> Mayor { get; set; }
            public DbSet<Company> Company { get; set; }
    
        }
    }
    

    在此项目

    AspEFCore.Domain.Models

    需要引用的依赖项如下:

    Microsoft.EntityFramework.Core
    Microsoft.EntityFramework.SqlServer

    编写相关表实体类:

    City表

    using System.Collections.Generic;
    
    namespace AspEFCore.DoMain.Models
    {
        public class City
        {
            /// <summary>
            /// 主键Id
            /// </summary>
            public int CityId { get; set; }
    
            /// <summary>
            /// 外键Id
            /// </summary>
            public int ProvinceId { get; set; }
    
            /// <summary>
            /// 导航属性
            /// </summary>
            public Province Province { get; set; }
    
            public IEnumerable<CityCompany> CityCompanies { get; set; }
            public Mayor Mayor { get; set; }
        }
    }

    Province表

    using System.Collections.Generic;
    
    namespace AspEFCore.DoMain.Models
    {
        public class Province
        {
            public int ProvinceId { get; set; }
            public IEnumerable<City> Cities { get; set; }
        }
    }

    Company表

    using System.Collections.Generic;
    
    namespace AspEFCore.DoMain.Models
    {
        public class Company
        {
            public int CompanyId { get; set; }
            public IEnumerable<CityCompany> CityCompanies { get; set; }
        }
    }

    CityCompany表

    namespace AspEFCore.DoMain.Models
    {
        public class CityCompany
        {
           public int CityCompanyId { get; set; }
    
            public int CityId { get; set; }
            public City City { get; set; }
    
            public int CompanyId { get; set; }
            public Company Company { get; set; }
        }
    }

    Mayor表

    namespace AspEFCore.DoMain.Models
    {
        public class Mayor
        {
            public int MayOrId { get; set; }
    
            public int CityId { get; set; }
            public City City { get; set; }
        }
    }

    AspEFCore.Web

    需要引用的依赖项如下:

    Microsoft.EntityFramework.Core.Tools

    Microsoft.EntityFramework.Core.Design

    需要引用的项目如下:

    AspEFCore.Domain.Models
    AspEFCore.Data

    appsettings.json文件中进行连接字符串的配置,配置如下:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "DefaultConnectionString": "Server =(localdb)\MSSQLLocalDB;Database=AspEFCoreDemo; Trusted_Connection=True"
      }
    }
    

    Startup.cs类的ConfigureServices方法进行连接字符串配置,配置如下:

     //配置数据库的连接字符串
     services.AddDbContext<MyContext>(option =>
     { 
      //option.UseSqlServer("Server =(localdb)\MSSQLLocalDB;Database=AspEFCoreDemo; Trusted_Connection=True");
                    option.UseSqlServer(_configuration.GetConnectionString("DefaultConnectionString"));
    });

    需要将数据库连接字符串所在项目设置为启动项 即 AspEFCore.Web设置为启动项.

    迁移

    打开Vs 的Nuget 程序包管理控制台,将EFCore上下文所在的项目设置为默认项目,即AspEFCore.Data 执行命令Add-Migrations生成迁移快照.
    执行成功

    再执行Update-Database命令,进行迁移
    执行成功

    查看生成的数据库:

    生成的数据库
    生成的数据库

    本文档参考自
    EntityFrameworkCore映射关系
    表关系

  • 相关阅读:
    webapi 中使用 protobuf
    apache httpclient cache 实现可缓存的http客户端
    编译nginx时提示undefined reference to 'pcre_free_study' 的问题及解决
    深入理解JVM内存回收机制(不包含垃圾收集器)
    从JDK源码理解java引用
    Buffer的创建及使用源码分析——ByteBuffer为例
    二叉树的子结构、深度以及重建二叉树
    数据结构——树与二叉树的遍历
    Java NIO之Buffer的使用
    Java多线程之synchronized详解
  • 原文地址:https://www.cnblogs.com/HelloZyjS/p/12700088.html
Copyright © 2020-2023  润新知