Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

entity framework - EntityFramework: using a view to extend a table

I'd like to use a view to add information to a table like this

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);
    }
}

But EntityFramework (core) isn't having any of it because:

The entity type 'PocoView' cannot be mapped to a table because it is derived from 'PocoTable'. Only base entity types can be mapped to a table.

Can this be made to work? Or can I do this some other way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...