简体   繁体   中英

SQL Server TPT Inheritance with Entity Framework 6 - DB First

I have an ASP.NET MVC project with EF6 and database first.

I have a table: "Survey" that is being used. Now, I need a new type of surveys that needs all fields of "Survey" and some new particular fields.

For that purpose, I thought about using inheritance. So I've created a new table "CourseSurvey" that has a primary key that is also a foreign key with reference to the primary key of "Survey" and some other non-nullable fields.

That seems to work fine.

When I need to check whether a row in "Survey" is an instance of "Survey" or "CourseSurvey" I do:

var survey = unitOfWork.SurveyRepository.FindSingleBy(m => m.SurveyId == viewModel.SurveyId) as CourseSurvey;

if(survey != null) {
   // then is a child
}

Is that a good practice?

Also, is it possible to convert an instance of "Survey" to "CourseSurvey"? If so, how should I do it?

And finally, am I doing the right thing here, or is there a better way of designing this? I could put "CourseSurvey" columns into "Survey" and allow them to be nullable, but I didn't want to pollute "Survey" with unused columns...

I'm now starting with this concept and I still feel that I'm not fully getting it.

Thanks!

I think you should use TPH, even keeping in mind that you will have columns, that are special for concrete class in the hierarchy. EF will create 'Discriminator' column and you will be able to use something like Fetch(m => m is CourseSurvey)

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