【问题标题】:How to design EF core code-first database when different tables share the same fields不同表共享相同字段时如何设计EF Core代码优先数据库
【发布时间】:2021-11-05 15:34:59
【问题描述】:

我正在开发一个带有 MS-SQL 数据库的 ASP .NET Core 5 MVC 应用程序,而 EF Core 是我的 ORM(采用代码优先方法)。

目前我正在重新设计数据库,我有多个共享许多相同属性的表,并且我希望能够从不同的表中添加/删除属性,但只能在代码中的一个位置。

因为 .NET 没有多类继承,所以我想出了在“层级”中继承类的想法。 基本上,在下面的示例中,purchasing 表和 products 表应该具有完全相同的价格、日期和内容属性,但还有一些额外的特定字段:

class Purchase : PriceDatesAndContent
{   
      // specific purchase properties
}

class Product : PriceDatesAndContent
{
      // specific product properties
}

class PricesDatesAndContent : PriceAndDates
{
       public string Name { get; set ; }
       public string Description { get; set; }
}

class PricesAndDates : Prices
{
      public DateTime someDate1 { get; set; }
      public DateTime someDate2 { get; set; }
      // ...
 }

class Prices
{
      public double Price1 { get; set; }
      public double Price2 { get; set; } 
}

但是,我不确定这在我看来是否真的是一个绝妙的主意,我很想听听您的意见,或者您甚至有针对这种情况的其他解决方法?

非常感谢!

【问题讨论】:

    标签: asp.net-mvc database entity-framework multiple-inheritance


    【解决方案1】:

    但是,我不确定这在我看来是否真的是一个绝妙的主意

    只要您的基类没有被映射为实体,就可以拥有较深的继承层次结构。但是不寻常以这种方式为你的类建模只是为了节省你自己的一点打字时间。

    使用接口对通用属性模式进行建模可能会更好,因此您不必将它们排列在单个层次结构中。例如

    public interface IHasName
    {
        public string Name { get; set; }
        public string Description { get; set; }
    }
    
    public interface IHasPrices
    {
        public double Price1 { get; set; }
        public double Price2 { get; set; } 
    }
    

    【讨论】:

    • 嗨,大卫,非常感谢!你能解释一下基类映射到实体的情况和不映射的情况有什么区别吗?
    • 当基类映射为实体时,它会影响关系设计。要么将整个层次结构映射到一个表,要么每个基类都有自己的表。这可能既昂贵又不方便。
    • 非常感谢。我决定为基本属性组和更复杂对象的抽象类编写一些接口。例如abstract class PurchaseBase : IHasPrice, IHasContent { //... } 然后每个实体将继承其相应的抽象类。非常感谢您的帮助!
    猜你喜欢
    • 2015-12-07
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    相关资源
    最近更新 更多