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

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

背景

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

  1. public class FooBarContext : DbContext
  2. {
  3. // ...
  4. public DbSet<FooReport> FooReport { get; set; }
  5. // ...
  6. }

哪里 FooReport 看起来像:

  1. public class FooReport
  2. {
  3. [Key]
  4. public int Id { get; set; }
  5. // ...
  6. }

问题/解决方法

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

  1. public partial class AddFooReport : Migration
  2. {
  3. protected override void Up(MigrationBuilder migrationBuilder)
  4. {
  5. // intentionally clear this out, so the entity isn't created / dropped as a table
  6. // migrationBuilder.CreateTable("FooReport", ... );
  7. }
  8. protected override void Down(MigrationBuilder migrationBuilder)
  9. {
  10. // intentionally clear this out, so the entity isn't created / dropped as a table
  11. // migrationBuilder.DropTable("FooReport");
  12. }
  13. }

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

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

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

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

nxowjjhe

nxowjjhe1#

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

csbfibhn

csbfibhn2#

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

  1. protected override void OnModelCreating(ModelBuilder modelBuilder)
  2. {
  3. modelBuilder.Entity<FooReport>().HasNoKey();
  4. //. . .
  5. }

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

  1. [Keyless]
  2. public class FooReport
  3. {
  4. public int Id { get; set; }
  5. // ...
  6. }
展开查看全部

相关问题