对EF Code First中的两个相同表使用相同类型 [英] Use same type against two identical tables in EF Code First

查看:90
本文介绍了对EF Code First中的两个相同表使用相同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,Users和TempUsers,我需要对它们两个进行操作。我已经定义了用户类型,并且要将其添加到两个表的DbContext中。问题是,它要么使用约定将类型名称映射到表,要么使用具有指定表名的TableAttribute。无论哪种方式,我都看不到如何添加两个将类型映射到不同表名的数据库集。

I have two tables, Users and TempUsers and I need to do operations on both of them. I already have my users type defined and I want to add it to the DbContext for both tables. Problem is, it either uses convention to map the type name to a table or using the TableAttribute with the table name specified. Either way I can't see how to add two dbsets mapping the type to different table names.

我可以使用复制+粘贴或通过UserBase类以及两个派生的User和TempUser类来复制类型。两种方法都可以使用,但实际上在我要处理用户的代码中,并且在代码中没有用户和TempUsers的复杂性。毕竟,存储库负责处理放置用户对象的位置,而业务逻辑不必处理它。

I could duplicate the type using either copy + paste or through a UserBase class and two derived User and TempUser classes. Both ways will work but really in the code I want to deal with Users and not have the complexity of Users and TempUsers in the code. After all it's the repository's responsibly to deal with where to put the user objects and the business logic shouldn't have to deal with it.

建议将不胜感激。谢谢!

Advice would be much appreciated. Thanks!

[基于注释的解释]

原因我有两个表是因为TempUsers支持批量导入/更新,但是每个用户都执行原子事务。因此,从外部进行某些Active Directory导出或进行此类导出将导致为每个用户调用服务。我必须创建/更新用户,并找出哪些未导入但已存在于数据库中的用户,然后将其删除。截断用户表并直接写入该表会更加简单,但是ID会有所不同,并且会断开用户到不同表的所有链接,例如运送历史记录。

推荐答案

这是不可能的。 EF无法在同一上下文中两次映射同一类。您的单个 User 类只能映射到 Users 表或 TempUsers 单个上下文类型中的表。您需要两个用户类或两个不同的上下文类型(具有不同的映射配置)-一种提供对 Users 表的访问,另一种提供对 TempUsers 表。

That is not possible. EF cannot map same class twice within same context. Your single User class can be only mapped to Users table or TempUsers table in single context type. You need either two user classes or two different context types (with different mapping configuration) - one providing access to Users table and second providing access to TempUsers table.

这篇关于对EF Code First中的两个相同表使用相同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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