zvz
zvz

Reputation: 193

Derived class used as a model in Entity Framework

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

Upvotes: 0

Views: 192

Answers (2)

Bron Davies
Bron Davies

Reputation: 6004

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

Upvotes: 2

YungDeiza
YungDeiza

Reputation: 4608

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

Upvotes: 1

Related Questions