繁体   English   中英

如何将相同 class 的两个列表拆分为实体框架中的不同表?

[英]How to split two lists of the same class to different tables in Entity Framework?

在我的项目中,我有以下课程:

public class Dot
{
    public int Id { get; set; }
    public int Value { get; set; }
    // some more information
}

public class TimeRow
{
    public int Id { get; set; }
    public List<Dot> Fact { get; set; }
    public List<Dot> Forecast { get; set; }
}

我希望FactForecast位于数据库的不同表中。 有什么好的方法吗?

我的想法

可能我可以创建两个类FactDotForecastDot ,它们继承 class Dot ,创建属性List<FactDot> FactList<ForecastDot> Forecast并且这些列表将位于不同的表中,但我认为这不是一个好的解决方案。

有一个没有从 Dot 继承的字段的预测 class。

public class Dot
{
    public int Id { get; set; }
    public int Value { get; set; }
    // some more information
}

public sealed class Forecast : Dot
{
}

public class TimeRow
{
    public int Id { get; set; }
    public List<Dot> Fact { get; set; }
    public List<Forecast> Forecast { get; set; }
}

这些列表将在不同的表中,但我认为这不是一个好的解决方案。

实际上,这是一个很好的解决方案。 :)

public class Dot
{
    public int Id { get; set; }
    public int Value { get; set; }
    // some more information
}

public class Fact : Dot
{ }

public class Forecast : Dot
{ }

public class TimeRow
{
    public int Id { get; set; }
    public virtual ICollection<Fact> Facts { get; set; } = new List<Fact>();
    public virtual ICollection<Forecast> Forecasts { get; set; } = new List<Forecast>();
}

为什么? 因为只是今天才觉得没有必要。 事实和预测看起来是一回事,所以有两个具有相同字段的类感觉“错误”。但它们不是一回事,即使它们目前看起来相同。 它们需要单独存储,谁能说未来不会有仅对这些实体之一真正有用的字段? 您不会想将可空的条件字段添加到 Dot 中,将特定于 Fact 的字段放入 Fact 中更有意义。 这使该途径保持完全开放。

如果添加从 Dot 扩展的其他类,那又如何呢? 它们实际上是两行代码,可以依赖 EF 约定进行映射。 :) 继承 Dot 只是一个合同,它们可以被视为“一个”Dot。 即使它们存储的数据还没有不同,它们仍然有自己独特的目的。

如果可能的话,最好只有一张桌子而不是两张。 它允许重用大量代码并使不同的查询更容易。 所以我推荐:

public class Dot
{
    public int Id { get; set; }
    public int Value { get; set; }

    public int TimeRowId { get; set; } 
    public int DotType {get; set;} in this case you can use 0-Fact, 1-Forecast
    // or maybe this: public string DotType {get; set;} in this case you can use just "Fact" or "Forecast"

....  // some more information
}

public class TimeRow
{
    public int Id { get; set; }
    public virtual List<Dot> Dots { get; set; }
  
}

或者在您的情况下,您会发现将 DotType 从 Dot 移动到 TimeRow class 会更好:


public class TimeRow
{
    public int Id { get; set; }
 public int DotType {get; set;} in this case you can use 0-Fact, 1-Forecast
    // or maybe this: public string DotType {get; set;} in this case you can use just "Fact" or "Forecast"

    public virtual List<Dot> Dots { get; set; }
  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM