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