4

Net6 EFcore框架介绍 - wskxy

 1 year ago
source link: https://www.cnblogs.com/wskxy/p/17179491.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Net6 EFcore框架介绍

  EFcore,可用使得开发人员不需要再去关注数据库的实现,全都由代码进行生成

  这样有利于减少工作量、数据库快速迁移...

2、上手搭建架构

  

1138839-20230304223916637-1067838103.png

  (这个图是做完本章内容的完整图,我们一步步深入即可)

  在写EF之前,先安装好数据库,我选择在本地安装Sqlserver

  我们先执行最核心的两步,将EF和数据库跑通

  1)类&表的定义:基本上会保持class和数据库的table字段保持一致,如上UserModel,我定义了Staff、Tenant两个类,会自动生成两个表

    UserModel需要安装

Microsoft.EntityFrameworkCore.SqlServer

    Staff

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace UserModel
{
    public class Staff
    {
        public int Id { get; set; }public string Name { get; set; }
        public string Description { get; set; }
        public string? PhoneNumber { get; set; }
        public string? Email { get; set; }
    }
}

    Tenant

namespace UserModel
{
    public class Tenant
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

  2)上下文定义:负责关联实体类、访问数据库配置,提供后续生成数据库支持,如上MyDBContextLibrary

  MyDBContextLibrary需要安装

Microsoft.EntityFrameworkCore.Tools

  MyDBContext

using Microsoft.EntityFrameworkCore;
namespace UserModel
{
    public class MyDBContext : DbContext
    {
        public DbSet<Staff> Staffs { get; set; }
        public DbSet<Tenant> Tenants { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=master;Integrated Security=True;TrustServerCertificate=yes");
        }
    }
}

  准备完毕!!

  打开【程序包管理器控制台】

  项目指定到MyDBContext

  

1138839-20230304231754762-673332835.png
Add-Migration Ini   #添加一个迁移  Ini是为这个迁移起的备注名
Update-database  #更新到数据库,执行了才会同步迁移到数据库

  到此,简单的EF框架已经跑起来了

  EF是一个十分强大的框架,我们逐渐扩展知识点。

  1)属性定义

  有两种方式

  其一:Data Annotations(数据注解),利用特性进行定义,如对Staff属性进行定义

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
//Data Annotations例子
namespace UserModel
{
    [Table("Staff")]//可用加特性指定表名
    public class Staff
    {
        public int Id { get; set; }
        [Required]//必填
        [MaxLength(10)]//最大长度为10
        public string Name { get; set; }
        [Required]
        public string Description { get; set; }
        public string? PhoneNumber { get; set; } //可空
        public string? Email { get; set; }
    }
}

  PS:提醒一点,Id / 类名+Id  在迁移到数据库表的时候,会默认为递增序列

  其二:Fluent API,微软官方提供的API,如对Tenant属性进行定义

  在MyDBContext,重写OnModelCreating方法

using Microsoft.EntityFrameworkCore;
namespace UserModel
{
    public class MyDBContext : DbContext
    {
        public DbSet<Staff> Staffs { get; set; }
        public DbSet<Tenant> Tenants { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=master;Integrated Security=True;TrustServerCertificate=yes");
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);modelBuilder.Entity<Tenant>().Property(x=>x.Description).IsRequired(false); /*指定Description非必填*/
        }
    }
}

  当然,我们容易看到,如果实体很多,属性直接写在这里代码太冗长了

  改变一下方法,添加一个TenantConfig类

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace UserModel
{
    public class TenantConfig : IEntityTypeConfiguration<Tenant>
    {
        public void Configure(EntityTypeBuilder<Tenant> builder)
        {
            builder.ToTable("Tenant");//可重新指定表名
            builder.HasKey(x => x.Id);
            builder.Property(x=>x.Name).IsRequired().HasColumnType("nvarchar(100)");
            builder.Property(x=>x.Description).IsRequired(false);
        }
    }
}

  然后  DbContext:

using Microsoft.EntityFrameworkCore;
namespace UserModel
{
    public class MyDBContext : DbContext
    {
        public DbSet<Staff> Staffs { get; set; }
        public DbSet<Tenant> Tenants { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=master;Integrated Security=True;TrustServerCertificate=yes");
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);modelBuilder.ApplyConfigurationsFromAssembly(typeof(Tenant).Assembly); //利用反射,加载Tenant程序集下的IEntityTypeConfiguration
        }
    }
}

  完成,再次生成一个迁移到数据库看看!!!

  代码不会一步到位的,大家逐步测试严重,这边我就不贴数据库的截图了

4、最后说明一下ConsoleApp

  Program

using UserModel;
using(var ctx = new MyDBContext())
{
    var s = new Staff()
    {
        Name = "kxy2",
        Description = "三好员工",
        PhoneNumber = "1234567890"
    };
    ctx.Staffs.Add(s);

    var t = new Tenant()
    {
        Name = "ccc",
    };
    ctx.Tenants.Add(t);
    ctx.SaveChanges();
}
Console.ReadLine();

  测试数据而已,怎么方便怎么来

  PS:有个点,如果设置ConsoleApp为启动项,迁移的时候会验证启动项的依赖,从而产生错误

  ConsoleApp需要安装

Microsoft.EntityFrameworkCore.Design

  至此,完成!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK