¿当使用继承和Entity Framework时,是否可以根据具体类将某些属性定义为“未映射”?
示例:
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"); }
}
}
所以我可以做类似的事情:
int GetTransportLenght(Guid transportId) {
Transport t = context.Transports.Where(t => t.Id == transportId).First();
return t.Length;
}
我也想做这样的事情:
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
}
某事告诉我您不应该这样做,但是我想知道……有什么方法可以使它工作?
很显然,如果上述想法违背了真理与美丽,那么我总能做到这一点(亲爱的读者,这可能是我应该做的,而不是浪费您的时间):
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; } }
}