Entity Framework (first code) - dynamic model building

I have an assembly with the classes of my domains - "Domains.dll". I dynamically add builds to the DbContext Dbset load classes.

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 a DataBase

 context.Database.Create(); 

This works, but with a problem for my domain. I have a class for a parent

 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 start the database - the table "Person" is not created. She creates the table "Objects" with the fields Id, FirstName, LastName.

If I change Person

 public class Person { public int Id {get; set;} public string FirstName {get ;set;} public string LastName {get ;set;} } 

then two tables are created in the database - "Man" and "Entities". How to use inheritance? How can I do it?

+3
source share
1 answer

Try using the [Table("Person")] attribute, and I recommend that you take a look at this Inheritance using EF Code First , this is a good post.

to resume the attempt:

 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;} } 
+4
source

Source: https://habr.com/ru/post/1381319/


All Articles