EFCore的基本配置使用

使用EFCore的功能,主要写三种文件:

1、实体类,Model类,对应数据库的数据字段:

 public class Book
    {
        public long Id { get; set; }
        public string Title { get; set; }
        public DateTime PubTime { get; set; }
        public decimal Price { get; set; }
        public string AuthorName { get;set; }
    }

2、实体字段配置类,对字段的长度,类型,精度进行配置:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace EFCore
{
    internal class BookConfiguration : IEntityTypeConfiguration<Book>
    {
        public void Configure(EntityTypeBuilder<Book> builder)
        {
            //指定表明,也可以不指定,不指定时使用Dbcontext中的属性明
            builder.ToTable("T_Books");
            //可以明确指定数据类型 和精度
            builder.Property(e => e.Price).HasColumnType("Decimal").HasPrecision(24, 6);
            builder.Property(e=>e.Title).HasMaxLength(50).IsRequired();
            //指定长度 和必填
            builder.Property(e=>e.AuthorName).HasMaxLength(20).IsRequired();
            //唯一索引
            builder.HasIndex(e => e.Title).IsUnique();
        }
    }
}

3、DBContext 类:

using Microsoft.EntityFrameworkCore;


namespace EFCore
{
    public class MyDbContext:DbContext
    {
        public DbSet<Book> Books { get; set; }
        /// <summary>
        /// 如果在配置里不使用 ToTable 指定表名,则使用这里的属性名作为表名
        /// </summary>
        public DbSet<Person> Persons { get; set; }
        public DbSet<Dog> Dogs { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            string server = "Data Source = .;Initial Catalog = EFCore;User Id = sa;Password = 123456;";
            optionsBuilder.UseSqlServer(server);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            //通过这句话就会加载所有的配置类 实现 IEntityTypeConfiguration
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }
    }
}

 

每次实体类变更或者配置变更后,

可以使用 Add-Migration 标识符  来提交变更。

在开发环境中 使用  Update-Database 将变更更新到数据库中,(或者升级到指定的版本)

对于正式运行环境,使用 Script-Migration A B  命令来生成从A版本升级到B版本需要的SQL语句。

 

同时可以通过 [__EFMigrationsHistory] 表来看当前系统升级到哪个阶段了。

 

 给字段做配置有两种方式: 

Code First Data Annotations

Fluent API - Configuring and Mapping Properties and Types

 推荐使用Fluent Api方式,虽然代码写的长一点,但配置更灵活,和model类解耦更好。

还可以在配置类中判断使用的数据库来做特殊的配置,而用 Data Annotations则无法配置

 

在配置中也进行不用ef的高级配置,可能不同数据库的兼容性不好,也不要和业务逻辑绑定太深。ef只是处理数据的增删改查

 

 

参考文档:

Fluent API - 配置和映射属性和类型 - EF6 | Microsoft Docs

Code First Data Annotations - EF6 | Microsoft Docs

posted @ 2022-07-19 22:35  百年俊少  阅读(694)  评论(0编辑  收藏  举报