简体   繁体   中英

LINQ Select New to create one table from super-type sub-type relationship

I'm working with a SQL database (still fairly new to it) and have attempted to create the "one-to-either" or sub-table supertable relationship. I'm using C# and LINQ-to-Entities.

As a common example I have 3 tables.

Person:
PersonId, Age, p1, p2, ..., pn

Student:
PersonId, Grade, GPA, s1, s2, ...., sn

Teacher:
PersonId, PrimarySubject, YearsAtSchool, IsCoach, ....

What I want to be able to do is query based on Person, and then get the relevant subtype data as well. I have the relevatn TypeId table to ensure the relationships.

Say if I queried a Person and they were a student, then I would like to get:

QueriedResult
PersonId, Age, p1, ..., pn, Grade, GPA, s1, ..., Sn 

Unfortunately, it is not feasibe to do select new {p.PersonID, etc} as there are too many subtables and too many elements in my case.

Whenever I use my code I get an IEnumerable of two seperate tables. The sample code I provide does return nulls when there is no associated student, and a table in the second column if the person is a student.

var query = (from p in Persons.AsEnumerable()
join s in Students on p.PersonId equals s.PersonId
select new {p, s});

I've heard alot of talk about 'flattening' though all the suggested methods seem to require p & s to be of the same table type.

Thanks,

You are struggling with modelliing inheritance. Student and Teacher both are Person s. There are several ways to store inherited classes in a relational database, and entity framework supports these.

The approach that probably helps you best is called Table per Concrete Type (TPC) , which means that each type has its own table in the database, while EF takes care of storing the subtypes in the right table. The link also refers the two other commmon approaches (TPH and TPT). TPT may also be appropriate, if your subclasses have relatively much in common.

So you would have

abstract class Person { PersonId, ... }

class Student : Person { Grade, ... }

class Teacher: Person { PrimarySubject, ... }

If you want Student s you do

context.Persons.OfType<Student>().Where(....

which gives you the QueriedResult result as intended.

Note that Person is abstract. If you want it to be concrete, you better make an abstract PersonBase class (or the like) and derive Person from it, just as Student and Teacher .

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