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。

 

转载于:https://www.cnblogs.com/dotnet261010/p/7419828.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值