用 Fluent API 设置元数据
http://agilenet.wordpress.com/2011/04/11/entity-framework-4-1-rc-with-an-existing-database/
-
03 | public int Id { get ; set ; } |
04 | public string CompanyName { get ; set ; } |
05 | public Country HomeCountry { get ; set ; } |
10 | public int Id { get ; set ; } |
11 | public string Code { get ; set ; } |
12 | public string Name { get ; set ; } |
public class MyContext: DbContext |
04 | public DbSet<Company> Companies { get ; set ; } |
05 | public DbSet<Country> Countries { get ; set ; } |
07 | public MyContext( string connectionString): base (connectionString) |
09 | Database.SetInitializer<MyContext>( null ); |
12 | protected override void OnModelCreating(DbModelBuilder modelBuilder) |
14 | modelBuilder.Configurations.Add( new CountryConfiguration()); |
15 | modelBuilder.Configurations.Add( new CompanyConfiguration()); |
16 | base .OnModelCreating(modelBuilder); |
public class CompanyConfiguration: EntityTypeConfiguration<Company> |
04 | public CompanyConfiguration(): base () |
10 | HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity). |
12 | Property(p => p.CompanyName). |
13 | HasColumnName( "Name" ). |
15 | HasRequired(x => x.HomeCountry). |
17 | Map(x => x.MapKey( "HomeCountryId" )); |
23 | public class CountryConfiguration: EntityTypeConfiguration<Country> |
26 | public CountryConfiguration(): base () |
31 | .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) |
34 | .HasColumnName( "Code" ) |
37 | .HasColumnName( "Name" ) |