首页 > 解决方案 > 实体框架继承,我可以根据具体类映射/不映射属性吗?

问题描述

¿ 使用继承和实体框架时,是否可以根据具体类将某些属性定义为未映射?

例子:

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

标签: c#.netentity-frameworkinheritanceorm

解决方案


推荐阅读