NaveenBhat
NaveenBhat

Reputation: 3318

Derive Auto-Generated Entity Class

I have a edmx file being set its Code Generation Strategy to None and a T4 template set to it, where I removed the Factory Method Creation logic. I have introduced some additional method for few of the entities on a separate file through partial class.

Ex: I have introduced few methods for the entity User on partial class and I derived the classes Admin and Person from User where I want to introduce some other methods.

The issue I'm facing here is, while assigning a value to the navigation property of Admin, it throws the exception Object mapping could not be found for Type with identity 'CivilRegistry.ControlledModel.Admin'.

User Class:

public partial class User
{

    protected static UserRepository repository = new UserRepository();

    public User Insert(User user)
    {
        user.AddedDate = DateTime.Now;
        user.AddedUserId = this.UserId;
        return repository.Insert(user);
    }
    //
    //Other methods goes here.
    //
}

Admin Class:

public class Admin : User
{
    public Admin() { }

    private Admin(User user)
    {
        this.UserName = user.UserName;
        //
        //Other properties
        //
        this.AddedUser = user.AddedUser; //This line throws, Exception.
    }

    public static Admin FindBy(int id)
    {
        //repository.FindByID returns an instance of User entity.
        return new Admin(repository.FindByID(user => user.UserId == id && user.RoleId == (int)RoleEnum.Admin));
    }
}

How can I resolve this?

Upvotes: 0

Views: 314

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

It is not supported. You cannot define entity in EDMX and then derive additional classes from the entity in your code. Derived classes created this way are not entities any more and cannot be retrieved or persisted by EF because EF doesn't know how to map them anymore.

The reason why it fails in assigning navigation property is that EF knows that Admin is User and it tries to attach it to the context but it doesn't find the Admin type in mapping (EDMX).

The solution is mapping the inheritance = moving your inheritance to EDMX where you will define User entity and derived Person and Admin entities. Here you have some tutorial.

Upvotes: 1

Related Questions