EF CodeFirst 学习 1 - 用fluent API设置元数据,

用 Fluent API 设置元数据

 

 

http://agilenet.wordpress.com/2011/04/11/entity-framework-4-1-rc-with-an-existing-database/

 

-

 

 

 

public class Company
02{
03public int Id { get; set; }
04public string CompanyName { get; set; }
05public Country HomeCountry { get; set; }
06}
07
08public class Country
09{
10public int Id { get; set; }
11public string Code { get; set; }
12public string Name { get; set; }
13}

 

 

 

public class MyContext: DbContext
02{
03
04public DbSet<Company> Companies { get; set; }
05public DbSet<Country> Countries { get; set; }
06
07public MyContext(string connectionString): base(connectionString)
08{
09Database.SetInitializer<MyContext>(null);
10}
11
12protected override void OnModelCreating(DbModelBuilder modelBuilder)
13{
14modelBuilder.Configurations.Add(new CountryConfiguration());
15modelBuilder.Configurations.Add(new CompanyConfiguration());
16base.OnModelCreating(modelBuilder);
17}
18
19}

 

 

 

public class CompanyConfiguration: EntityTypeConfiguration<Company>
02{
03
04public CompanyConfiguration(): base()
05{
06
07HasKey(p => p.Id);
08Property(p => p.Id).
09    HasColumnName("Id").
10    HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).
11    IsRequired();
12Property(p => p.CompanyName).
13    HasColumnName("Name").
14    IsRequired();
15HasRequired(x => x.HomeCountry).
16    WithMany().
17    Map(x => x.MapKey("HomeCountryId"));
18ToTable("Companies");
19}
20
21}
22
23public class CountryConfiguration: EntityTypeConfiguration<Country>
24{
25
26public CountryConfiguration(): base()
27{
28HasKey(p => p.Id);
29    Property(p => p.Id)
30    .HasColumnName("Id")
31    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
32    .IsRequired();
33Property(p => p.Code)
34    .HasColumnName("Code")
35    .IsRequired();
36Property(p => p.Name)
37    .HasColumnName("Name")
38    .IsRequired();
39ToTable("Countries");
40}
41
42}

 

 

 

posted on 2011-06-13 23:14  bela liu  阅读(676)  评论(0编辑  收藏  举报

导航