将多个表映射到实体框架中的单个实体类

Chr*_*ath 28 c# entity-framework c#-4.0 entity-framework-4.1 asp.net-mvc-3

在此之前被标记为重复,我已检查其他相关的帖子,他们不回答我的问题.

我正在处理一个遗留数据库,该数据库有2个具有1:1关系的表.目前,我为每个定义的表都有一个类型(1Test:1Result)我想将这些特定的表合并为一个类.

目前的类型看起来像这样

public class Result 
{
    public          string      Id                  { get; set; }
    public          string      Name                { get; set; }
    public          string      Text                { get; set; }
    public          string      Units               { get; set; }
    public          bool        OutOfRange          { get; set; }
    public          string      Status              { get; set; }
    public          string      Minimum             { get; set; }
    public          string      Maximum             { get; set; }

    public virtual  Instrument  InstrumentUsed      { get; set; }

    public virtual  Test        ForTest             { get; set; }
}


public class Test
{
    public          int     Id            { get; set; }
    public          string  Status        { get; set; }
    public          string  Analysis      { get; set; }
    public          string  ComponentList { get; set; }
    public virtual  Sample  ForSample     { get; set; }
    public virtual  Result  TestResult    { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我希望他们看起来像这样

public class TestResult
{
    public          int        Id              { get; set; }
    public          string     Status          { get; set; }
    public          string     Analysis        { get; set; }
    public          string     ComponentList   { get; set; }
    public          string     TestName        { get; set; }
    public          string     Text            { get; set; }
    public          string     Units           { get; set; }
    public          bool       OutOfRange      { get; set; }
    public          string     Status          { get; set; }
    public          string     Minimum         { get; set; }
    public          string     Maximum         { get; set; }

    public virtual  Instrument InstrumentUsed { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我目前正在使用流畅的API将这些API映射到我们的旧Oracle数据库.

将这些组合成一个类的最佳方法是什么?请注意,这是一个旧数据库.更改表格不是一个选项,在项目的这一点上创建视图不是一个可行的解决方案.

Era*_*nga 36

如果两个表中具有相同的主键,则可以使用Entity Splitting来实现此目的.

  modelBuilder.Entity<TestResult>()
    .Map(m =>
      {
        m.Properties(t => new { t.Name, t.Text, t.Units /*other props*/ });
        m.ToTable("Result");
      })
    .Map(m =>
      {
        m.Properties(t => new { t.Status, t.Analysis /*other props*/});
        m.ToTable("Test");
      });
Run Code Online (Sandbox Code Playgroud)

这是一篇有用的文章

  • @KarthicG 没有。EF Core 6 仍然不支持将多个表映射到单个实体 - 但如果您使用数据库优先(而不是代码优先),那么您可以使用“VIEW”将表连接在一起并对 EF Core 和小指撒谎- 发誓“VIEW”实际上是一个“TABLE” - 这是完全有效的,因为您可以在 SQL Server 中为“VIEW”对象定义“INSERT”和“UPDATE”处理程序。 (3认同)