具有相同 POCO 类的多个表

本文关键字:POCO | 更新日期: 2023-09-27 18:36:34

我有一个现有的数据库,其中有四个相同且不相关的表。

我想使用相同的 POCO 类来描述所有四个类,而不必创建同一类的副本。

到目前为止,这是我的上下文:

class StatsContext : DbContext
{
    // [MagicTableAttribute( "map_ratings_vsh" )] -- does something like this exist?
    public DbSet<MapRatings> MapRatingsVSH { get; set; }
    public DbSet<MapRatings> MapRatingsJump { get; set; }
    // 2 more tables using same class
}
class MapRatings
{
    public string SteamID { get; set; }
    public string Map { get; set; }
    public int Rating { get; set; }
    [Column( "rated" )]
    public DateTime Time { get; set; }
}

我的问题是现有表被命名为"map_ratings_vsh"和"map_ratings_jump",我不能使用TableAttribute的数据注释,因为它只能在类上使用。

有没有其他方法——也许是流畅的 api——来描述我的架构?

具有相同 POCO 类的多个表

我发现解决这个问题的一种方法是使用继承。

[Table("map_ratings_vsh")]
public class MapRatingsVSH : MapRatingsBase {}
[Table("map_ratings_jump")]
public class MapRatingsJump : MapRatingsBase {}
public class MapRatingsBase
{
    public string SteamID { get; set; }
    public string Map { get; set; }
    public int Rating { get; set; }
    [Column( "rated" )]
    public DateTime Time { get; set; }
}

然后,您可以让 DbContext 如下所示:

public class StatsContext : DbContext
{
    public DbSet<MapRatingsVSH> MapRatingsVSH { get; set; }
    public DbSet<MapRatingsJump> MapRatingsJump { get; set; }
}

EF 理解这是两个不同的表应该没有任何问题,即使实现将位于同一位置 ( MapRatingsBase

您可以使用流畅的 api 将某些属性映射到一个表,将其他属性映射到另一个表,如下所示:

modelBuilder.Entity<TestResult>()
    .Map(m =>
    {
        m.Properties(t => new { /* map_ratings_vsh columns */ });
        m.ToTable("map_ratings_vsh");
    })
    .Map(m =>
    {
        m.Properties(t => new { /* map_ratings_jump columns */ });
        m.ToTable("map_ratings_jump");
    });

我过去处理这个问题的(hacky)方法是使用存储过程或视图返回数据,然后在 DbContext 实现上提供"AddEntity"或"SaveEntity"方法,该方法持久化有问题的实体