Davor
Davor

Reputation: 1396

Base class in Entity Framework 6?

I have a lot of generic methods in my program that take some generated entity as parameter. So, methods like:

public void DoHerpDerp<EntityType>()

While this is fine and does the job, users of my methods can still pass whatever they want as generic parameter (and crash the application). I want to strictly limit them to entity generated objects (I'm using Database First approach). What I want to write is something like:

public void DoHerpDerp<EntityType>() where EntityType : BaseEntity

Is there such class as BaseEntity, and if the isn't one, how do I work around this? And no, I'm not gonna write 200 partial classes that implement an interface.

Upvotes: 4

Views: 4418

Answers (1)

boindiil
boindiil

Reputation: 5865

You could change the generation of the entities by adapting the T4 template.

Here is the relevant part of the T4 template (e.g. Model.tt) for generating the class declaration, e.g. "partial class MyEntity":

public string EntityClassOpening(EntityType entity)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1}partial class {2}{3}",
        Accessibility.ForType(entity),
        _code.SpaceAfter(_code.AbstractOption(entity)),
        _code.Escape(entity),
        _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)));
}

to

public string EntityClassOpening(EntityType entity)
{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1}partial class {2}{3}{4}",
        Accessibility.ForType(entity),
        _code.SpaceAfter(_code.AbstractOption(entity)),
        _code.Escape(entity),
        _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)),
        string.IsNullOrEmpty(_code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))) ? _code.StringBefore(" : ", "BaseClass") : "");
}

In this example, every class which has no super-class is generated as a sub-class of BaseClass which you may implement as you wish.

Upvotes: 8

Related Questions