Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework (Code First) - Dynamically Building a Model

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?

like image 736
FetFrumos Avatar asked Mar 23 '23 00:03

FetFrumos


1 Answers

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;}
} 
like image 125
Swift Avatar answered Apr 10 '23 21:04

Swift