Ric*_*ugh 1 entity-framework entity-framework-core
我想使用视图将信息添加到这样的表中
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但 EntityFramework(核心)没有任何这些,因为:
实体类型“PocoView”无法映射到表,因为它是从“PocoTable”派生的。只有基本实体类型可以映射到表。
这可以发挥作用吗?或者我可以用其他方式做到这一点吗?
You can use HasBaseType(Type) method and pass null to let EF Core not treat PocoTable as base entity (part of database inheritance) of PocoView, e.g.
modelBuilder.Entity<PocoView>()
.HasBaseType((Type)null) // <--
.ToView("PocoView");
Run Code Online (Sandbox Code Playgroud)