【问题标题】:Entity Framework Core: Combine owned properties with inheritanceEntity Framework Core:将拥有的属性与继承结合起来
【发布时间】:2018-01-15 09:26:53
【问题描述】:

给出以下类:

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

我想将这些类映射到以下表格布局。我使用的是 Entity Framework Core Preview 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/ 但这似乎不能与继承结合使用,至少我找不到示例。

有人知道如何将拥有的属性与继承结合起来吗?

【问题讨论】:

  • 拥有的类型不支持继承。

标签: c# .net entity-framework .net-core entity-framework-core


【解决方案1】:

你能不能这样做:

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

这样,这些值与表架构匹配,但默认为空值。或者你可以这样做:

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

    public class RuleAction1 : RuleAction
    {            
    }

    public class RuleAction2 : RuleAction
    {            
    }

我可能会走得更远,抱歉,如果这只会拖慢你的速度。

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 2014-08-20
    • 2020-02-25
    • 1970-01-01
    • 2021-05-17
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多