c# - 实体框架继承,我可以根据具体类映射/不映射属性吗?
问题描述
¿ 使用继承和实体框架时,是否可以根据具体类将某些属性定义为未映射?
例子:
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; } }
}
解决方案
推荐阅读
- python - 用于验证科学记数法的 RegEx
- docker - 从 docker-compose 连接到不同堆栈上的服务
- c# - ViewModel 中 MVC asp.net 中的自定义验证
- c# - 可能将数据库连接到服务器
- laravel - 登录后 Laravel 一直在注销我
- netlogo - 使用特殊?变量 Netlogo 什么是替代方案?
- excel - 如何从每日报告中的先前条目中提取数据?
- angular - Angular Promise .then() 返回值
- c++ - 仅当模板参数为真时 C++ 创建变量
- r - gsub("[[:space:]]+", " ", x) 中的错误:'Calloc' 无法分配内存(226427 个字节)