简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM