.Net core 3.x无键实体类型避免创建表 [英] .Net core 3.x Keyless Entity Types avoid table creation

查看:390
本文介绍了.Net core 3.x无键实体类型避免创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在实体框架核心3.1.1中执行复杂的sql查询,在研究中我发现无键实体类型是采用代码优先方法的方式。我看到了很多有关dbquery的文档,但是在.net core 3.x中被标记为过时了。

I need to execute a complex sql query in entity framework core 3.1.1, on researching i found out that keyless entity types is the way to go in code first approach. I see lot of documents for dbquery but this is marked as obsolete in .net core 3.x

无密钥实体类型

根据Microsoft文档中的说明dbquery已过时,因此请改用dbset方法,但是对于dbset,它正在尝试在数据库中创建新表。如何在应用迁移时禁用无密钥实体类型中的表生成?

As per Microsoft documentation it says dbquery is obsolete so use dbset approach instead, but with dbset it is trying to create a new table in database. how to disable table generation in keyless entity types while applying migrations?

示例代码

public class ApplicationContext : DbContext
{
 public DbSet<CustomQuery> CustomQuery { get; set; }
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
    modelBuilder.Ignore<CustomQuery>();
    modelBuilder.Entity<CustomQuery>().HasNoKey();
 }
}

.net core 2.2

with .net core 2.2

var entity = _context.Query<CustomQuery>().FromSqlRaw(Regex.Unescape(selectQuery)).AsNoTracking().FirstOrDefault();

具有.net core 3.1

with .net core 3.1

var newEntity = _context.CustomQuery.FromSqlRaw(Regex.Unescape(selectQuery)).AsNoTracking().FirstOrDefault();

如果我尝试应用迁移,则将以自定义查询的名义创建一个新表,但是我不需要这种事情发生。因为这只是一个用于保存联接查询中的值的模型,而我不会插入,更新或删除此表中的值。

if i try to apply migrations then a new table in the name of custom query is being created, but I don't need this to happen. because this is just an model used to hold the values from the join query and i will not insert, update or delete the values in this table. how to achieve this?

还是针对这种情况有更好的方法。

or is there any better approach for this situation.

推荐答案

这是EF Core 3中的一个已知缺陷,在此处报告 3.0升级-具有HasNoKey的实体()(以前是查询类型)在添加迁移#18116 时尝试创建表。

This is a known defect in EF Core 3, reported here 3.0 Upgrade - Entity with HasNoKey() (formerly a query type) tries to create tables when adding migration #18116.

To vs从方法:建议合理化ToTable,ToQuery,ToView,FromSql和其他相关方法#17270 能够从迁移中排除/跳过/忽略模型的某些部分,从而不会创建表(对于重叠的有界上下文)#2725 ,两者均计划在5.0版本中发布,这意味着最终可以通过解决该问题来解决该问题

Closed as "duplicate" of To vs From methods: Proposal to rationalize ToTable, ToQuery, ToView, FromSql, and other related methods #17270 and Ability to exclude/skip/ignore parts of the model from migrations so that a table is not created (for overlapping bounded contexts) #2725, both scheduled for 5.0 release, which means it would eventually be addressed in that release.

当前解决方法在 EF核心团队成员之一发表了= noreferrer>评论


现在,您可以使用类似 .ToView(您忘记将FromSql与ModQueueEntry一起使用)

或更一般地,使用 .ToView(null),例如

or more generally, using .ToView(null), e.g.

modelBuilder.Entity<CustomQuery>().HasNoKey().ToView(null);

这篇关于.Net core 3.x无键实体类型避免创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆