首页 > 代码库 > CodeFirst中DbContext动态添加DbSet
CodeFirst中DbContext动态添加DbSet
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(); } } } }
CodeFirst中DbContext动态添加DbSet
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。