Entity Framework (Code First) - Dynamically Building a Model

c#, code-first, dynamic, entity-framework, model

Solution

Try using `[Table("Person")]` Attribute, and I encourage you to take a look at that Inheritance with EF Code First, It is a good post.

so to resume try this:

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;}
} 

Problem

I have an assembly with classes my domains - "Domains.dll". I dynamically add to my DbContext Dbset load classes of assembly. ``` 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[] { }); } } } ``` Next, I create DataBase ``` context.Database.Create(); ``` This works but with a problem for my domain. I have a class for the parent entity ``` public abstract class Entity { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } } public class Person : Entity { public string FirstName {get ;set;} public string LastName {get ;set;} } ``` If now I run a database - table 'Person' is not create.It creates a table 'Entities' with fields Id, FirstName, LastName. If I change the Person ``` public class Person { public int Id {get; set;} public string FirstName {get ;set;} public string LastName {get ;set;} } ``` then created in the database two tables - 'Person' and 'Entities'. How do I use inheritance? How do I do it right?

Original source