简体   繁体   中英

Map to class based on property value

Say I have two classes

class Employee 
{
    public string EmployeeId { get; set; }
    public int Manager { get; set; }
}

class Manager : Employee 
{

}

where int Manager can be either 1 or 0 . I want to create a mapping in my EmployeeContext so that employee entries in the employee table, where manager equals 1, are mapped to the Manager class.

You need to implement a TPH inheritance pattern as described here . What you need to add to the described implementation is - you need to include the Discriminator property in your entity classes and map it to the according database field. Then implement your int Manager according to the value of the Discriminator property - and Manager can only be a read-only property.

If you want to make the employee a manager you must change the value of the Discriminator field. In turn, you must be aware of what's happening in your db. TPH is far from the silver bullet and you might want to use another pattern, but this one is good to start with.

See also: Entity Framework Inheritance Mapping (TPH) and How to map inherited entities in EF code-first .

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