Entity Framework(五):使用配置伙伴创建数据库
在上一篇文章中讲了如何使用fluent API来创建数据表,不知道你有没有注意到一个问题。上面的OnModelCreating方法中,我们只配置了一个类Product,也许代码不是很多,但也不算很少,如果我们有1000个类怎么办?都写在这一个方法中肯定不好维护。EF提供了另一种方式来解决这个问题,那就是为每个实体类单独创建一个配置类。然后在OnModelCreating方法中调用这些配置伙伴类。
创建Product实体类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data.Entity.ModelConfiguration; 6 7 namespace EF配置伙伴.Model 8 { 9 public class Product 10 { 11 public int ProductNo { get; set; } 12 13 public string ProductName { get; set; } 14 15 public double ProductPrice { get; set; } 16 } 17 }
创建Product实体类的配置类:ProductMap,配置类需要继承自EntityTypeConfiguration泛型类,EntityTypeConfiguration位于System.Data.Entity.ModelConfiguration命名空间下,ProductMap类如下:
1 using EF配置伙伴.Model; 2 using System; 3 using System.Collections.Generic; 4 using System.Data.Entity.ModelConfiguration; 5 using System.Linq; 6 using System.Text; 7 8 namespace EF配置伙伴.EDM 9 { 10 public class ProductMap :EntityTypeConfiguration<Product> 11 { 12 public ProductMap() 13 { 14 // 设置生成的表名称 15 ToTable("ProductConfiguration"); 16 // 设置生成表的主键 17 this.HasKey(p => p.ProductNo); 18 // 修改生成的列名 19 this.Property(p =>p.ProductNo).HasColumnName("Id"); 20 this.Property(p => p.ProductName) 21 .IsRequired() // 设置 ProductName列是必须的 22 .HasColumnName("Name"); // 将ProductName映射到数据表的Name列 23 24 } 25 } 26 }
在数据上下文Context类的OnModelCreating()方法中调用:
1 using EF配置伙伴.EDM; 2 using EF配置伙伴.Model; 3 using System; 4 using System.Collections.Generic; 5 using System.Data.Entity; 6 using System.Linq; 7 using System.Text; 8 9 namespace EF配置伙伴.EFContext 10 { 11 public class Context:DbContext 12 { 13 public Context() 14 : base("DbConnection") 15 { } 16 17 public DbSet<Product> Products { get; set; } 18 protected override void OnModelCreating(DbModelBuilder modelBuilder) 19 { 20 // 添加Product类的配置类 21 modelBuilder.Configurations.Add(new ProductMap()); 22 base.OnModelCreating(modelBuilder); 23 } 24 25 26 } 27 }
查看数据库,可以看到符合我们的更改:
这种写法和使用modelBuilder是几乎一样的,只不过这种方法更好组织处理多个实体。你可以看到上面的语法和写jQuery的链式编程一样,这种方式的链式写法就叫Fluent API。
分类:
Entity Framework
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决