将poco/entity添加到dbcontext以进行自定义查询/过程,而不首先在实体框架代码中创建表

axkjgtzd  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(569)

背景

我使用efcore3作为一个应用程序,在dbcontext中有许多poco,我想将其创建为数据库表-这里没有问题!我使用linq查询在这里获取数据,生活是美好的。
我还有一些原始sql查询和一些更复杂的报告过程。我为返回的数据创建了poco,并将其作为dbset添加到dbcontext中:

public class FooBarContext : DbContext
{
    // ...

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

    // ...
}

哪里 FooReport 看起来像:

public class FooReport
{
    [Key]
    public int Id { get; set; }

    // ...
}

问题/解决方法

这将创建一个迁移来创建一个名为 FooReport ,这不是我想要的。
我现在的解决方法是从 Migration 因此,本质上,我有一个空迁移:

public partial class AddFooReport : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        // intentionally clear this out, so the entity isn't created / dropped as a table

        // migrationBuilder.CreateTable("FooReport", ... );
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        // intentionally clear this out, so the entity isn't created / dropped as a table

        // migrationBuilder.DropTable("FooReport");
    }
}

然后我可以这样调用程序:

var result = this._fooBarContext.Set<FooReport>(@"[SP_FooReport]")
    .FromSqlRaw(sql)
    .ToList();

这确实管用,但似乎有点老套。
我还尝试通过添加 NotMapped 装饰工 FooReport 但是查询本身失败了。

热释光;博士;-你能把dbset定义为一个实体而不是一个表吗?

nxowjjhe

nxowjjhe1#

你可以尝试添加 modelBuilder.Ignore<FooReport>(); 呼叫 OnModelCreating 方法 FooReportNotMapped 属性。

csbfibhn

csbfibhn2#

在efcore3+中,只需从fooreport中删除键,使其成为无键实体类型

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

 modelBuilder.Entity<FooReport>().HasNoKey();
 //. . .

}

在ef 5中也有这样一个属性:

[Keyless]
public class FooReport
{
    public int Id { get; set; }

    // ...
}

相关问题