实体框架核心:将拥有的属性与继承相结合



给定的是以下类:

public class Rule
{
public long Id { get; set; }
public string Filter { get; set; }
public RuleAction Action { get; set; }
}
public abstract class RuleAction
{
}
public class RuleAction1 : RuleAction
{
public string Value { get; set; }
}
public class RuleAction2 : RuleAction
{
public decimal Percent { get; set; }
}

我想将这些类映射到以下表布局。我使用实体框架核心预览版 2。

Table "Rule"
- Id
- Filter
- ActionDiscriminator
- Value // only set if the object in Action is typeof(RuleAction1)
- Percent // only set if the object in Action is typeof(RuleAction2)

重要的部分是"操作"没有映射到单独的表。我知道我可以将属性映射为"拥有财产",如本文 (OwnsOne( 中所述:https://blogs.msdn.microsoft.com/dotnet/2017/06/28/announcing-ef-core-2-0-preview-2/但这似乎不能与继承结合使用,至少我找不到示例。

有人知道如何将拥有的财产与继承相结合吗?

你能做这样的事情吗:

public class RuleAction1 : RuleAction
{
public string Value { get; set; }
public decimal Percent { get; set; } = null;
}
public class RuleAction2 : RuleAction
{
public decimal Percent { get; set; }
public string Value { get; set; } = null;
}

这样,这些值与表架构匹配,但仅默认为 null 值。 或者你可以做这样的事情:

public abstract class RuleAction
{
public string Value { get; set; } = null;
public decimal Percent { get; set; } = null;
}
public class RuleAction1 : RuleAction
{            
}
public class RuleAction2 : RuleAction
{            
}

我可能会很远,对不起,如果这只会减慢你的速度。

最新更新