我的域有一个类(在程序集中“Domains.dll”)。我动态地将程序集的加载类添加到我的 DbContext Dbset 中。
public class MyContext : DbContext
{
public MyContext() : base("DBConnection"){}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Assembly assembly = Assembly.LoadFrom("Domains.dll");
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
var list = assembly.GetTypes().OrderBy(i => i.GetType().Name);
foreach (Type item in list)
{
entityMethod.MakeGenericMethod(item)
.Invoke(modelBuilder, new object[] { });
}
}
}
public abstract class Entity
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
[Table("Person")]
public class Person : Entity
{
public string FirstName {get ;set;}
public string LastName {get ;set;}
}
创建新数据库后,我添加了新的人。无法在字段 Id 中插入空值的错误。自动增量不起作用。如果我不添加动态实体将创建一个空数据库,那么代码将起作用。
public class PersonContext: DbContext
{
public PersonContext() : base("DBConnection"){}
public IDbSet<Person> Persons { get; set; }
}
using (PersonContext context = new PersonContext())
{
Person user = new Person
{
FirstName = "first",
LastName = "last"
};
context.Persons.Add(user);
context.SaveChanges();
}
可能是什么问题呢?多少是自动增量不起作用?