最近在封装EF过程中,所有实体继承BaseDomain,然后在Context类中反射所有实体
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null
&& type.BaseType.BaseType != null
&& type.BaseType.BaseType.IsGenericType
&& type.BaseType.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)
).ToList();
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
public class Person : BaseDomain
{
public string Name { get; set; }
public string ID { get; set; }
public bool Sex { get; set; }
public int Age { get; set; }
public string Country { get; set; }
}
public class Dog : BaseDomain
{
public string Name { get; set; }
public string ID { get; set; }
public int Age { get; set; }
}
....//其他各种实体
在第三方调用的时候,可以反射获取所有实体的Type类型,现在问题是,通过
type获取反射的实例无法转为对应实体的强类型,不知道有没有好的方案。
//模拟反射到的实体类型Type
var type=typeof(Person);
//获取实体的实例,由于下面的仓储要求必须实体派生自BaseDomain,这里
var entity =Activator.CreateInstance(type) as BaseDomain;
var resp = new RepoModel();
var count = resp.InsertModel(entity);//这里报错“The entity type BaseDomain is not part of the model for the current context.”
//entity改为如下就可以
entity =Activator.CreateInstance(type) as Person;