Entity Framework 配置关系(1对N)

  这里介绍1:N配置关系。

  举例说明:酒店连锁Chain下面有多个酒店Hotel。从酒店连锁的角度来观察,酒店连锁Chain与Hotel的关系是一个酒店连锁对应多个酒店(1:N)。从酒店的角度来观察,一个酒店对应1个酒店连锁(1:1)。

(1)实体类

 1 public class Chain
 2 {
 3     public int Id { get; set; }
 4 
 5     public string Name { get; set; }
 6 
 7     public virtual ICollection<Hotel> Hotels { get; set; }
 8 }
 9 
10 public class Hotel
11 {
12     public int Id { get; set; }
13 
14     public string Name { get; set; }
15 
16     public virtual Chain Chain { get; set; }
17 }

(2)映射

 1 // ChainMap
 2 using System.ComponentModel.DataAnnotations.Schema;
 3 using System.Data.Entity.ModelConfiguration;
 4 
 5 namespace EntFra01
 6 {
 7     public class ChainMap : EntityTypeConfiguration<Chain>
 8     {
 9         public ChainMap()
10         {
11             this.ToTable("Chain");
12             this.HasKey(p => p.Id);
13 
14             this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
15             this.Property(p => p.Name).IsRequired().HasMaxLength(63);
16         }
17     }
18 }
19 
20 // HotelMap
21 using System.ComponentModel.DataAnnotations.Schema;
22 using System.Data.Entity.ModelConfiguration;
23 
24 namespace EntFra01
25 {
26     public class HotelMap : EntityTypeConfiguration<Hotel>
27     {
28         public HotelMap()
29         {
30             this.ToTable("Hotel");
31 
32             this.HasKey(p => p.Id);
33 
34             this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
35             this.Property(p => p.Name).IsRequired().HasMaxLength(63);
36 
37             this.HasRequired(h => h.Chain)
38                 .WithMany(c => c.Hotels)
39                 .Map(m => m.MapKey("ChainId"))
40                 .WillCascadeOnDelete(true);
41         }
42     }
43 }
44 
45 // DbContext
46 using System.Data.Entity;
47 
48 namespace EntFra01
49 {
50     public class EntFraContext : DbContext
51     {
52         public IDbSet<Chain> ChainSet { get; set; }
53 
54         public IDbSet<Hotel> HotelSet { get; set; }
55 
56         protected override void OnModelCreating(DbModelBuilder modelBuilder)
57         {
58             modelBuilder.Configurations.Add(new ChainMap());
59             modelBuilder.Configurations.Add(new HotelMap());
60 
61             base.OnModelCreating(modelBuilder);
62         }
63     }
64 }

(3)生成效果

 

posted @ 2015-05-14 21:08  lcyan  阅读(156)  评论(0编辑  收藏  举报