Entity Framework Fluent API (2)
在前一篇博客中,介绍了Entity Framework Fluent API的使用。把所有的实体类的映射都写在了DbContext的OnModelCreating中。但是如果一个应用中的实体类有很多,那么使用这种方式,把所有的实体类的映射都写在了一起,不方便管理。这里介绍另外一种使用方式,可以更加模块化的管理这些配置。
完整代码
(1)实体类:Chain
1 public class Chain
2 {
3 public int Id { get; set; }
4
5 public string Name { get; set; }
6 }
(2)实体类:Hotel
1 public class Geolocation
2 {
3 public double Longitude { get; set; }
4
5 public double Latitude { get; set; }
6 }
7
8 public class Hotel
9 {
10 public int Id { get; set; }
11
12 public string Name { get; set; }
13
14 public string Address { get; set; }
15
16 public byte[] RowVersion { get; set; }
17
18 public Geolocation Geolocation { get; set; }
19
20 public string Remark { get; set; }
21 }
(3)实体类映射:ChainMap
1 public class ChainMap : EntityTypeConfiguration<Chain>
2 {
3 public ChainMap()
4 {
5 this.ToTable("Chain");
6
7 this.HasKey(p => p.Id);
8
9 this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
10 this.Property(p => p.Name).IsRequired().HasMaxLength(63);
11 }
12 }
(4)实体类映射:HotelMap
1 public class HotelMap : EntityTypeConfiguration<Hotel>
2 {
3 public HotelMap()
4 {
5 this.ToTable("Hotel");
6
7 this.HasKey(p => p.Id);
8
9 this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
10 this.Property(p => p.Name).IsRequired().HasMaxLength(63);
11 this.Property(p => p.Address).HasMaxLength(127);
12 this.Property(p => p.RowVersion).IsRowVersion();
13
14 this.Ignore(p => p.Remark);
15 }
16 }
17
18 public class GeolocationMap : ComplexTypeConfiguration<Geolocation>
19 {
20 public GeolocationMap()
21 {
22 this.Property(p => p.Longitude).IsOptional().HasColumnName("Longitude");
23 this.Property(p => p.Latitude).IsOptional().HasColumnName("Latitude");
24 }
25 }
(5)数据上下文:DbContext
1 public class EntFraContext : DbContext
2 {
3 public IDbSet<Chain> Chains { get; set; }
4
5 public IDbSet<Hotel> Hotels { get; set; }
6
7 protected override void OnModelCreating(DbModelBuilder modelBuilder)
8 {
9 modelBuilder.Configurations.Add(new ChainMap());
10 modelBuilder.Configurations.Add(new HotelMap());
11
12 base.OnModelCreating(modelBuilder);
13 }
14 }

浙公网安备 33010602011771号