zoukankan      html  css  js  c++  java
  • EFCore 2.0的IEntityTypeConfiguration<TEntity>的使用!

    通过新建一个类来实现  IEntityTypeConfiguration 这个接口,将EFCore中的实体配置写在单独的配置类中,便于修改和维护。

      OnModelCreating代码:

        

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
    
                modelBuilder.Entity<Class>().ToTable("T_Classs");
    
                modelBuilder.Entity<Teachers>().ToTable("T_Teachers");
    
                //modelBuilder.Entity<Students>()    //这是EF 2.0之前版本将配置写在OnModelCreating方法中的写法
                //    .ToTable("T_Students")
                //    .HasOne(s => s.Class)
                //    .WithMany(e => e.Students)
                //    .HasForeignKey(e => e.ClassId);
    
                modelBuilder.ApplyConfiguration(new StudentCofig());  //这是将单独的配置类注册到OnModelCreating中
    
                modelBuilder.ApplyConfiguration(new TeacherClassConfig());
                   
    
            }

      新建的实体配置类:

      

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata.Builders;
    using MyEF2.Models;
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace MyEF2.Configuration
    {
        public class StudentCofig : IEntityTypeConfiguration<Students>  //继承该接口
        {
            public void Configure(EntityTypeBuilder<Students> builder)
            {
                builder.ToTable("T_Students")
                    .HasOne(s => s.Class)
                    .WithMany(e => e.Students)
                    .HasForeignKey(e => e.ClassId);
            }
        }
    }

      最后在MyDbContext中的OnModelCreating方法中注册:

        

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
    
                modelBuilder.Entity<Class>().ToTable("T_Classs");
    
                modelBuilder.Entity<Teachers>().ToTable("T_Teachers");
    
                modelBuilder.ApplyConfiguration(new StudentCofig());  //这是将单独的配置类注册到OnModelCreating中
    
                modelBuilder.ApplyConfiguration(new TeacherClassConfig());
                   
    
            }

        

  • 相关阅读:
    nodeJS入门01-http模块
    nodeJS入门-Buffer对象
    php与MySQL(php内置mysql函数)
    php与MySQL(基本操作)
    log4net
    js验证小数类型(浮点数)和整数类型
    牛腩学ASP.NET CORE做博客视频
    opencv再学习之路(八)---设定感兴趣区域(RIO)
    opencv再学习之路(四)---色彩分割得到二值图像
    opencv再学习之路(三)---形态学操作
  • 原文地址:https://www.cnblogs.com/ROOKIEDEBUG/p/9289263.html
Copyright © 2011-2022 走看看