具有相同POCO类的多个表

Rya*_*ker 5 c# entity-framework ef-code-first entity-framework-4.1

我有一个现有的数据库,我有四个相同和无关的表.

我想使用相同的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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

jst*_*ick 8

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

[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; }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以让你的DbContext看起来像:

public class StatsContext : DbContext
{

    public DbSet<MapRatingsVSH> MapRatingsVSH { get; set; }

    public DbSet<MapRatingsJump> MapRatingsJump { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

EF应该没有任何问题,理解这些是两个不同的表,即使实现将在同一个地方(MapRatingsBase)