EF Code First - 实体连接多个表
我目前有一个由数据库视图支持的 EF 类(连接多个表)。为了使其可更新,我需要将类更改为由数据库表支持。我正在使用 Entity Framework 4.1 Code First,但不知道如何设置这些关系?
为了简化,我当前有一个类别类,它返回类别名称(Categories 表)和类别类型名称(CategoryTypes 表)。这些都在我当前使用的数据库视图中。我想更改为 ViewModel,直接从表中带回这两个字段并正确连接,这样当用户更新类别名称时,EF 应该能够正确处理更新(因为它将更新表)的视图)。有关如何执行此操作的任何提示?
I currently have an EF class that is backed by a database view (joining multiple tables). To make it updatable, I need to change the class to be backed by a database table. I am using Entity Framework 4.1 Code First and can't figure out how to set up those relationships?
To simplify, I currently have a Categories class that returns the Category Name (Categories table) and Category Type Name (CategoryTypes table). These are both in the database view that I currently use. I want to change to a ViewModel that brings back both of these fields directly from their tables and joins properly, that way when a user updates a Category Name, EF should be able to properly handle the update (since it will be updating the table instead of the view). Any tips on how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
表是一个表——它是一个单一的数据库对象。如果您想删除视图并将其替换为表,则需要删除当前表(
Categories
和CategoryTypes
)并创建一个包含非规范化数据的表。这是一个非常糟糕的解决方案,它会导致整个应用程序出现问题。只是为了简化描述:不可能用一个表替换由多个表之间的联接构造的视图,也不可能使您的视图可更新。
您做错了,因为您显然将视图模型直接映射到数据库。将
Categories
和CategoryTypes
映射到实体,加载Category
及其CategoryType
并将它们展平到应用程序逻辑中的视图模型(或通过投影加载视图模型)。一旦用户更新您的视图模型,请将其分解回单独的实体并保存它们。Table is a table - it is a single database object. If you want to remove your view and replace it with a table you need to delete your current tables (
Categories
andCategoryTypes
) and create a single table which will contain denormalized data. That is pretty bad solution and it will cause you problems in the whole application.Just to simplify description: It is not possible to replace your view constructed by joins among several tables with a table and it is not possible to make your view updatable.
You are doing it wrong because you are obviously mapping view models directly to your database. Map
Catagories
andCategoryTypes
to entities loadCategory
with itsCategoryType
and flatten them to your view model in your application logic (or load the view model through projection). Once user updates your view model decompose it back to separate entities and save them.