简体   繁体   English

具有现有数据库视图的实体框架代码优先

[英]Entity Framework Code First with an existing database view

My team is starting a new project using Entity Framework Code First.我的团队正在使用 Entity Framework Code First 开始一个新项目。 We have a new, empty database for the project;我们为该项目创建了一个新的空数据库; the schema will be managed through Code First migrations.该架构将通过 Code First 迁移进行管理。

However, there is one piece of data that we will need to access that lives in an external database (managed by a different project).但是,我们需要访问位于外部数据库(由不同项目管理)中的一段数据。 We were given access to this data through a view in our own database that maps to a table in the external database.我们可以通过我们自己数据库中的一个视图访问这些数据,该视图映射到外部数据库中的一个表。

Because of this setup, we have two competing requirements:由于这种设置,我们有两个相互竞争的要求:

  1. When creating migrations, Entity Framework should not try to create or edit the view.当创建迁移,实体框架不应尝试创建或编辑视图。
  2. At runtime, we should still be able to query/insert/update/delete data through the view using Entity Framework as if it is a regular table.在运行时,我们应该仍然能够使用实体框架通过视图查询/插入/更新/删除数据,就像它是一个普通表一样。

We've looked at both the [NotMapped] attribute and the .Ignore() method, but both seems to only satisfy one of the two requirements above.我们已经查看了[NotMapped]属性和.Ignore()方法,但两者似乎都只满足上述两个要求之一。

Is this configuration possible using Entity Framework Code First, or will we need to switch to Database First?这种配置是否可以使用实体框架代码优先,还是我们需要切换到数据库优先?

We're using Entity Framework Core version 2.1.1.我们使用的是 Entity Framework Core 2.1.1 版。

There is no configuration which satisfies both requirements, and I don't see how Database First (or Code Second) would help, since the problem is with migration, not mapping.没有满足这两个要求的配置,我不知道数据库优先(或代码第二)会如何帮助,因为问题在于迁移,而不是映射。

The requirement #2 can easily be satisfied by mapping the view as table (either conventionally, [Table] data annotation or ToTable fluent API).通过将视图映射为表(通常是[Table]数据注释或ToTable fluent API),可以轻松满足需求 #2。 For EF CRUD operations it really doesn't matter if the actual db object with that name is a table or view, as soon as it supports the corresponding SQL commands.对于 EF CRUD 操作,只要它支持相应的 SQL 命令,具有该名称的实际 db 对象是表还是视图并不重要。

The requirement #1 cannot be satisfied by the above solution, but can easily be workaround.上述解决方案无法满足要求 #1,但可以轻松解决。 Since EF Core requires pre created code migrations (no automatic migrations like EF6), you can manually edit the migrations which contains CreateTable in Up / DropTable in Down and simply remove them.由于 EF Core 需要预先创建的代码迁移(没有像 EF6 那样的自动迁移),您可以手动编辑包含Up中的CreateTable / Down DropTable的迁移,然后简单地删除它们。

Actually there is also a solution based on custom MigrationSqlGenerator , but it's more complicated and doesn't worth the effort just for a single view.实际上也有一个基于自定义 MigrationSqlGenerator的解决方案,但它更复杂,不值得为单个视图付出努力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM