Home > OS >  Derived class used as a model in Entity Framework
Derived class used as a model in Entity Framework

Time:06-24

I have a class in a different project and want to extend that class to another project with Entity Framework. Is this possible? Will it generate a table with the properties from the base class?

Example:

IUser.cs (from project with no Entity Framework)

public interface IUser
{
     string Username { get; init; }
     string Password { get; init; }
}

User.cs (from project with no Entity Framework)

public class User : IUser
{
     string Username { get; init; }
     string Password { get; init; }
}

UserDB.cs (from project with Entity Framework)

public class UserDB : User 
{
     public int Id { get; set; }
}

CodePudding user response:

Yes, EF would see UserDB as a class that had the properties: Id, Username and Password.

CodePudding user response:

In EF Core this works automatically. In EF for legacy .NET projects you have to map the inherited properties inside of OnModelCreating() like this:

            var mapping = modelBuilder.Entity<UserDB>();
            mapping.Map(m =>
            {
                m.MapInheritedProperties();
            });

Otherwise, the database table will not store the properties of the User class

  • Related