Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class and Interface hierarchies in Entity Framework?

I have two related classes which share a common interface and are both stored in the same underlying database table. However, the Entity Framework generates one common class, where I really need the two distinct classes. How do I resolve this? Is it best to use a base class rather than an interface? How do I change the EF model to provide two classes mapped over one table?

Edit: the AccountType property determines the type of class; user or group.

Some simple code:

public interface IAccount
{
    string Name { get; set; }
    AccountType AccountType { get; set; }
}

public class GroupAccount : IAccount
{
    public string Name { get; set; }
    public GroupType GroupType { get; set; }
    public AccountType AccountType { get; set; }
}

public class UserAccount : IAccount
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }
    public AccountType AccountType { get; set; }
}
like image 909
flesh Avatar asked Dec 09 '08 16:12

flesh


People also ask

What are the three types of Entity Framework?

There are three approaches to model your entities in Entity Framework: Code First, Model First, and Database First. This article discusses all these three approaches and their pros and cons.

What is entity class in Entity Framework?

An entity in Entity Framework is a class that maps to a database table. This class must be included as a DbSet type property in the DbContext class. Entity Framework API maps each entity to a table and each property of an entity to a column in the database.

What is TPH in Entity Framework?

Table-per-hierarchy and discriminator configuration. By default, EF maps the inheritance using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents.


1 Answers

Is this data discriminated? i.e. does AccountType define which type it is? If so:

  • EF should create the Account entity from the storage
  • you then create 2 subclasses (UserAccount and GroupAccount)
  • in the mapping for Account, specify a predicate "add a condition"
    • have it map to UserAccount where the AccountType (storage) field is 1 (or whatever)
    • have it map to GroupAccount where the AccountType (storage) field is 2 (or whatever)

The account type then should completely disappear from the Account object (unmap it if not). To get just the UserAccount records, you use

 .Accounts.OfType<UserAccount>()...

The Account class should probably be abstract in this model. The interface stuff can be added via a partial class - i.e. in a separate file, define:

partial class Account : IAccount {
   // extra code here
}

etc

A reasonable walkthrough is here.

like image 183
Marc Gravell Avatar answered Oct 13 '22 05:10

Marc Gravell