Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

bottleneck using entity framework inheritance

so first my entities

Entities

the problem i want to have a page with all the story titles and their types

there are three stories LongStory , CoOpStory, GenericStory

the generic story is associated with StoryType for the type of the generic story

i have two problems

first when i want to check if the story is LongStory or CoOpStory i have to get all the entity and check the entity type if it is LongStory then do something , i don't know how to retrieve some data [only the title] and check the type

my second problem like i said i want to have a page with all the story titles and their types i don't know how to do that without making a lot of queries , i can't make a join to the StoryType table because it must be GenericStory to be associated with that , so what i do first get all the stories then do an extra query for every GenericStory to get the type

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are looking of OfType and Concat extension methods.

To get only LongStory instances you just need to call:

var longStories = context.Stories.OfType<LongStory>().ToList();

To get your bigger query it is little bit more complex. You can either try:

var allStories = context.Stories
                        .OfType<GenericStory>()
                        .Include("StoryType") // I'm not sure how this works with concat
                        .Concat(
                             context.Stories.OfType<LongStory>.Concat(         
                                  context.Stories.OfType<CoOpStory>()));

Or you can do a projection:

var allStories = context.Stories
                        .OfType<GenericStory>()
                        .Select(s => new { s.Title, s.StoryType.Name })
                        .Concat(
                             context.Stories
                                    .OfType<LongStory>
                                    .Select(s => new { s.Title, "LongStory" })
                                    .Concat(         
                                        context.Stories
                                               .OfType<CoOpStory>()
                                               .Select(s => new { s.Title, Type })));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...