使用EFCore 自动生成两个表外键的方法

在这里插入图片描述
在这里插入图片描述

建2个表, 导入到数据库中

在EFCore中配置 先不配置外键

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

namespace SelectDemon
{
    public class Model1
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Number { get; set; }
        //public Model2 Model2 { get; set; } //没有对应外键时候注释掉
        public int Model2Id { get; set; }

    }
}

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

namespace SelectDemon
{
    public  class Model2
    {
        public int Id { get; set; }
        public string OtherInfo { get; set; }
        public int Number { get; set; }
        //public List<Model1> Model1s { get; set; } //没有对应外键时候注释掉

    }
}

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SelectDemon
{
    //多
    public class Model1Config : IEntityTypeConfiguration<Model1>
    {
        public void Configure(EntityTypeBuilder<Model1> builder)
        {
            builder.ToTable("Model1");
            builder.HasKey(x => x.Id);
            //一对一
            //builder.HasOne<Model2>(m=>m.Model2).WithOne(a=>a.Model1).HasForeignKey<Model1>(m=>m.Model2Id);
            
            //一对多 没有外键时注释掉
            //builder.HasOne<Model2>(m => m.Model2).WithMany(a => a.Model1s).HasForeignKey(m => m.Model2Id);
        }
    }
}

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SelectDemon
{
    public class MyDbContext : DbContext
    {
        public DbSet<Model1> Model1s { get; set; }
        public DbSet<Model2> Model2s { get; set; }

        private ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();
        IConfiguration configRoot;
        string connString;

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            cfgBuilder.AddJsonFile("Config.json", optional: true, reloadOnChange: true);
            configRoot = cfgBuilder.Build();
            connString = configRoot.GetSection("ConnectionStrings:SqliteConnectionString").Value;

            optionsBuilder.UseSqlite(connString);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }
    }
}

建立表1对表2的外键:


//Console.WriteLine("Hello, World!");

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using SelectDemon;

using (MyDbContext db = new MyDbContext())
{
    //m1 为list, 外键在m1中, 外键为m2的Id:Model2Id.
    //如果二者有相同的number值, m1中的Model2Id 等于Model2的ID
    var m1 = db.Model1s; //多

    var m3 = db.Model2s;//一
    Dictionary<int, int> t1 = new Dictionary<int, int>();
    foreach (var item in m3)
    {
        t1.Add(item.Number,item.Id);
    }


    foreach (var item in m1)
    {
        if (t1.ContainsKey(item.Number))
        {
            item.Model2Id = t1[item.Number];
        }
    }
    db.SaveChanges();
}



之后把外键加上

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

namespace SelectDemon
{
    public class Model1
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Number { get; set; }
        public Model2 Model2 { get; set; } //没有对应外键时候注释掉
        public int Model2Id { get; set; }

    }
}

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SelectDemon
{
    //多
    public class Model1Config : IEntityTypeConfiguration<Model1>
    {
        public void Configure(EntityTypeBuilder<Model1> builder)
        {
            builder.ToTable("Model1");
            builder.HasKey(x => x.Id);
            //一对一
            //builder.HasOne<Model2>(m=>m.Model2).WithOne(a=>a.Model1).HasForeignKey<Model1>(m=>m.Model2Id);
            
            //一对多 没有外键时注释掉
            builder.HasOne<Model2>(m => m.Model2).WithMany(a => a.Model1s).HasForeignKey(m => m.Model2Id);
        }
    }
}

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

namespace SelectDemon
{
    public  class Model2
    {
        public int Id { get; set; }
        public string OtherInfo { get; set; }
        public int Number { get; set; }
        public List<Model1> Model1s { get; set; } //没有对应外键时候注释掉

    }
}

然后数据迁移即可

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

	<ItemGroup>
		<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
		<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.3" />
		<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.3">
			<PrivateAssets>all</PrivateAssets>
			<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
		</PackageReference>
		<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.3" />
		<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.3" />
		<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3">
			<PrivateAssets>all</PrivateAssets>
			<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
		</PackageReference>
		<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
		<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
		<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
		<PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" />
		<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
		<PackageReference Include="NModbus4.NetCore" Version="2.0.1" />
		<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
	</ItemGroup>

	<ItemGroup>
	  <None Update="Config.json">
	    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
	  </None>
	</ItemGroup>

</Project>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值