【问题标题】:EntityFramework: using a view to extend a tableEntityFramework:使用视图扩展表
【发布时间】:2021-10-25 17:11:22
【问题描述】:

我想使用视图将信息添加到这样的表中

public class PocoTable
{
    public int Id { get; set; }
}

public partial class ImportStatingRecordError : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(@"
CREATE VIEW PocoView
AS
    SELECT Id, ISNULL(l.InterestingValue, '?') AS InterestingValue
    FROM PocoTable t
        LEFT JOIN OtherTable o ON t.Id = o.PocoTableId
");
    }
}

public class PocoView : PocoTable
{
    public string InterestingValue { get; set; }
}

public class ApplicationDbContext : DbContext
{
    public DbSet<PocoTable> PocoTables { get; set; }
    public DbSet<PocoView> PocoViews { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<PocoView>().ToView("PocoView").HasKey(z => new z.Id);
    }
}

但 EntityFramework(核心)没有它,因为:

实体类型“PocoView”无法映射到表,因为它派生自“PocoTable”。只有基本实体类型可以映射到表。

这可以工作吗?或者我可以通过其他方式做到这一点吗?

【问题讨论】:

  • 你可以使用一个接口来定义结构和实现两个类的ist。然后你可以映射 View-class 并且在使用 Interface 时可以 Target 两者。

标签: entity-framework entity-framework-core


【解决方案1】:

您可以使用HasBaseType(Type) 方法并传递null 让EF Core 不将PocoTable 视为PocoView 的基础实体database inheritance 的一部分),例如

modelBuilder.Entity<PocoView>()
    .HasBaseType((Type)null) // <--
    .ToView("PocoView");

【讨论】:

    【解决方案2】:

    这也有效:

    public abstract class PocoBase 
    {
      public int Id { get; set; }
    }
    
    [Table("PocoTable ")]
    pubic class PocoTable : PocoBase {}
    
    public class PocoView : PocoBase 
    {
      public string InterestingValue { get; set; }
    }
    

    哪个更好?

    【讨论】:

    • 这总是有效的,而且想法是一样的——共享基础 class 而不是基础 entity。没有“更好”,因为这两种方法都有效并实现了预期目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2014-07-23
    相关资源
    最近更新 更多