5

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?

1
  • I know this thread is very old! But did you get this problem running? With auto-updating database? Commented Sep 8, 2016 at 9:37

1 Answer 1

7

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;}
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.