3

我有一个项目,我在 EF 中将其定义EmployerUser. 在我的过程中,我创建了一个用户,但不知道它最终是否会成为雇主(或其他类型的用户),然后我需要转换它。起初我试过(智能感知表明存在显式转换):

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

4

2 回答 2

7

这不可能。您必须始终使用最终类型。一旦将其创建为User,EF 将永远不允许您将其更改为派生实体类型。

顺便提一句。面向对象的方法也是不可能的。您不能将父类的实例强制转换为派生类的实例(除非它确实是派生类的实例) - 它会在运行时抛出异常。重现问题的非常简单的示例:

class X { } 

class Y : X { }

class Program 
{
    static void Main(string[] args) 
    {
        X x1 = new Y();
        Y y1 = (Y)x1;   // Works

        X x2 = new X();
        Y y2 = (Y)x2;   // InvalidCastException
    }
}

做到这一点的唯一方法是覆盖转换运算符,它将在内部创建派生类的新实例并将所有字段从旧父实例复制到新的派生实例。

实体框架需要完全相同的方法。如果您从User实体开始,现在要将其提升为Employer实体,则必须删除旧用户并创建新的Employer.

于 2011-09-01T07:39:32.453 回答
0

假设您的 Employer 实体只有可为空的属性,则可以转到数据库中的表并将鉴别器从 User 更改为 Employer。所有的关系都会被保留。也有可能做相反的事情。

于 2014-02-22T01:22:38.640 回答