How can I use a class under LINK and TPT EF?

I have the following class hierarchy:

public class RealPeople { } public class Users : RealPeople { } public class People : RealPeople { } 

In my dbContext, I defined dbSet for RealPeople and in the OnModelCreating procedure, I specified shared tables for people and users:

 modelBuilder.Entity<Users>().ToTable("Users"); modelBuilder.Entity<People>().ToTable("People"); 

This creates an appropriate complete hierarchy in my database with three matching tables. The problem occurs when I want to get the Users list in my database. It:

 List = (from Reg in PersistentMgr.RealPeople select (Users)Reg) .ToList(); 

or that:

 List = (from Reg in PersistentMgr.RealPeople select (Users)((RealPeople)Reg)) .ToList(); 

Throws an exception:

LINQ can only use primitive model types.

So, I can not attribute RealPeople to the corresponding Users subclass. Any ideas on this?

+7
source share
2 answers

The method of obtaining a collection of subclasses is used OfType :

 var users = (from p in PersistentMgr.RealPeople select p).OfType<User>(); 
+9
source

Try this instead:

 var list = PersistentMgr.RealPeople.Select(reg => reg as Users).ToList(); 

it's better:

 var list = PersistentMgr.RealPeople.Select(reg => (reg is Users) ? reg as Users : null).ToList(); 

You will get the same error if you try this:

 var realperson = new RealPeople(); var user = (Users) realperson; 

The reason is that the compiler does not know how to convert complex types to their subtypes using a simple cast - so you need to use the keyword instead. This will result in either a null return or a supertype entered in the subtype.

 var realperson = new RealPeople(); var user = realperson as Users; // user is realperson converted into a Users object var aString = "this is a string"; var otheruser = aString as Users; // otheruser is null, because aString was not a valid supertype for Users 
+4
source

All Articles