Entity Framework 6 - inheritance and navigation properties on base class

☆樱花仙子☆ 提交于 2019-12-04 19:06:16

Remove the Users and Workers collection properties.

public virtual ICollection<User> Users { get; set; }

public virtual ICollection<Worker> Workers { get; set; }

As your Company navigation property is defined on Person the associated back navigation property has to be an ICollection of Person.

The People collection will contain all the associated workers and users. The two extra properties Users and Workers are interpreted as completely new relationships and because you do not have corresponding properties and foreign keys on User or Worker EF generates it virtually.

Answer to the comment. Just for the sake of formatting as a second answer ;-)

With eager loading if you start with the Company

var companies = db.Company.Include(p => p.People);

It will always get the Users and the Workers.

If you use eager loading starting at the people.

var users = db.People.OfType<User>().Include(p => p.Company).ToList();
var companies = users.Select(p => p.Company).Distinct().ToList();

the People navigation property of your companies has just the Users.

Also you could execute two separate statements and the fixup of the database context will automatically fill the Navigation properties.

var company = db.Company.Where(p => p.ID > 100).ToList();
var copanyUsers = db.Company.Where(p => p.ID > 100)
                      .SelectMany(p => p.People).OfType<User>().ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!