snappymcsnap
snappymcsnap

Reputation: 2103

Entity Framework with a base entity class

Our team is working on implementing a code-first EF framework over an extensive existing database schema. One of the things we would really like to have is a base interface which all our different entities will implement. All that we intend to define in this basic interface is an Id field and a Name field since all our database tables have some concept of both of these properties. There are a lot of benefits to this approach because there are a great many cases in our application where all you need from an object is its Id and some descriptive text (its 'Name') so being able to program to the interface rather than to the implementation can provide quite a bit of flexibility.

The problem arises because not all the tables in our schema have integer-based PKs, some have strings, guids, etc. So there's no way we can define a true 'type' for the Id field in our interface other than object that can accommodate all the possibilities. The issue then becomes that EF doesn't like the idea of an object as its PK so it complains when trying to specify HasKey(o => o.Id).

Is there anyway that you guys can think of to accomplish what we are trying to pull off here? Thanks!

Upvotes: 2

Views: 4038

Answers (1)

cadrell0
cadrell0

Reputation: 17307

Use generics.

public interface IEntityBase<TKey>
{
    TKey Id { get; set; }
    string Name { get; set; }
}

Then you can implement it like this

public class IntKeyEntity : IEntityBase<int>
{
    int Id { get; set; }
    string Name { get; set; }
}

public class StringKeyEntity : IEntityBase<string>
{
    string Id { get; set; }
    string Name { get; set; }
}

//etc

Upvotes: 8

Related Questions