我有一个项目,我在 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 具有持久性时,我怎么能沮丧?