using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.ModelConfiguration.Configuration; namespace CodeFirstDemo { /// <summary> /// 实体注册Helper接口 /// </summary> public interface IEntityRegstHelper { void RegTo(ConfigurationRegistrar confRegistrar); } // 客户 public class Customer { public int CustomerID { get; set; } public String CustomerName { get; set; } public string Address { get; set; } } // 客户实体的注册Helper public class CustomerRegstHelper : IEntityRegstHelper { public void RegTo(ConfigurationRegistrar confRegistrar) { confRegistrar.Add<Customer>(new EntityTypeConfiguration<Customer>()); } } public class MyDbContext : DbContext { List<IEntityRegstHelper> entityRegstHelperlist; // 添加实体注册 public void AddEntityRegHelper(IEntityRegstHelper r) { if (entityRegstHelperlist == null) entityRegstHelperlist = new List<IEntityRegstHelper>(); entityRegstHelperlist.Add(r); } //public DbSet<Customer> Customers { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // 动态地加入实体 if (entityRegstHelperlist != null) { foreach (IEntityRegstHelper r in entityRegstHelperlist) r.RegTo(modelBuilder.Configurations); } } } class Program { static void Main(string[] args) { using (var db = new MyDbContext()) { db.AddEntityRegHelper(new CustomerRegstHelper()); var c = new Customer() { CustomerName = "长沙市大风通讯有限公司", Address = "长沙市" }; db.Set<Customer>().Add(c); db.SaveChanges(); var query = from customer in db.Set<Customer>() select customer; foreach (var cq in query) { Console.WriteLine("客户: {0}, 地址:{1}", cq.CustomerName, cq.Address); } Console.WriteLine("按任意键退出"); Console.ReadKey(); } } } }