【发布时间】:2011-11-08 04:08:53
【问题描述】:
我有一个项目,我在 EF 中将Employer 定义为User 的派生类。在我的过程中,我创建了一个用户,但不知道它最终是否会成为雇主(或其他类型的用户),然后我需要转换它。一开始我试过(智能感知表明存在显式转换):
Employer e = (Employer) GetUser();
但在运行时我得到了:
Unable to cast object of type 'System.Data.Entity.DynamicProxies.User_7B...0D' to type 'Employer'.
所以我尝试写一个转换器:
public partial class User
{
public static explicit operator Employer(User u)
{
但我得到了错误:
Error 21 'User.explicit operator Employer(User)': user-defined
conversions to or from a derived class are not allowed
C:\Users\..\Documents\Visual Studio 2010\Projects\..\Website\Models\EF.Custom.cs
很好。然后我重载了Employer 的构造函数,如下所示:
public partial class Employer
{
public Employer(User u)
{
this.Id = u.Id;
this.Claims = u.Claims;
// etc.
}
}
然后我想我可以这样做:
Employer e = new Employer(GetUser());
但是当我运行它时,我得到了错误:
System.InvalidOperationException was unhandled by user code
Message=Conflicting changes to the role 'User' of the
relationship 'EF.ClaimUser' have been detected.
Source=System.Data.Entity
StackTrace:
[...]
at Controllers.AuthController.Register(String Company, String GivenName,
String Surname, String Title, String Department) in C:\Users\..\Documents\
Visual Studio 2010\Projects\..\Website\Controllers\AuthController.cs:line
作为最后的手段,我尝试写这个:
Employer e = Auth.Claims("id")
.Where(x => x.Value == Auth.NameIdentifier())
.Select(x => x.User)
.Cast<Employer>()
.Single();
... GetUser() 返回一个 User 类型的对象,它不提供 .Cast<> 所以我使用直接查询到达那里...但我仍然得到动态代理对象异常的强制转换。
所以我的问题是:当对象通过 EF 具有持久性时,我该如何向下转型?
【问题讨论】:
-
Employer是您的 EF 模型的一部分吗?如果您已将继承正确映射为TPH或TPC,则 EF 将实例化正确的子类代理 -
@Eranga,是的
Employer是 EF 模型的一部分。我正在使用 TPT,所以我有一张名为Users的表和一张名为Users_Employer
标签: c# entity-framework asp.net-mvc-3 casting downcast