0

¿When using inheritance and Entity Framework, is it possible to define some properties as Not mapped depending on the concrete class?

Example:

public abstract class Transport
{
    [Key]
    public Guid Id { get; set; }

    public string PlateNumber { get; set; }

    // [NotMapped] ??
    public abstract int Length { get; set; } // This property may or may not be mapped
}

public class Car : Transport
{
    public string Model { get; set; }

    // [MapThisOnePlease]
    public override int Length { get; set; } // For cars, I want this in the DB
}

public class Train : Transport
{
    public int WagonCount { get; set; }

    [NotMapped] // No mapping for trains, it is calculated
    public override int Length {
        get { return this.WagonCount * 15; }
        set { throw new NotSupportedException("Length is readonly for Trains"); }
    } 
}

So I can do something like:

int GetTransportLenght(Guid transportId) {
    Transport t = context.Transports.Where(t => t.Id == transportId).First();
    return t.Length;
}

I also would like to do something like this:

List<Car> GetCarsLongerThan(int length) {
    return context.Cars.Where(c => c.Length > length).ToList();//if I try this with a train EF won't be happy
}

Something tells me that you are not supposed to do this, but I wonder… is there a way to make it work?

Obviously, if the idea above goes against truth and beauty, I can always do this (which is probably what I should be doing instead of wasting your time, dear reader):

public abstract class Transport
{
    [Key]
    public Guid Id { get; set; }

    public string PlateNumber { get; set; }

    [NotMapped]
    public abstract int TotalLength { get; }
}

public class Car : Transport
{
    public string Model { get; set; }

    public int Length { get; set; }

    public override int TotalLength { get { return this.Length; } }
}

public class Train : Transport
{
    public int WagonCount { get; set; }

    public override int TotalLength { get { return this.WagonCount * 15; } }
}
Gelu
  • 955
  • 2
  • 11
  • 21
  • Related question about [attribute inheritance](https://stackoverflow.com/questions/1240960/how-does-inheritance-work-for-attributes) and [this one](https://stackoverflow.com/questions/3840196/c-sharp-override-an-attribute-in-a-subclass) seems a duplicate – Cleptus Sep 17 '19 at 09:57
  • If you do not want the entity table to have the specified column, You can ignore the property in entity framework fluent api configuration. Example: modelBuilder.Entity().Ignore(x=>x.TotalLength) will not add the TotalLength property to table – codein Sep 17 '19 at 10:25

0 Answers0