Question

I'm having troubles getting this right...

I have a "Core" project with a common set of functionality including for instance Tagging. Tagging includes a set of entities some of which include Tag and ObjectTag.

They basically look like this:

Tag       (uniqueidentifier TagId, nvarchar(max) Tag)
ObjectTag (uniqueidentifier TagId, uniqueidentifier ObjectId)

My "Core" project also contains a data model with DbContext called CoreEntities. So I can do the following:

from ot in CoreEntities.Tag select ot where ot.TagId = "{someguid}"

I also have a "Web" project which includes object specific to my website for instance Recipe. Recipe looks like this:

Recipe    (uniqueidentifier RecipeId, string Name)

My "Web" project also has a data model with corresponding context (WebEntities) which makes the following possible:

var recipes = from r in WebEntities.Recipe 
              select r 
              where r.Name == "Granny's Meatloaf"

foreach(var r in recipes) {
    var recipeTags = from t in CoreEntities.ObjectTag 
                     select t 
                     where t.ObjectId == r.RecipeId
}

This is pretty resource intensive as for every Recipe the corresponding ObjectTag records have to be fetched. When trying to join the entities I got the following error: "The specified LINQ expression contains references to queries that are associated with different contexts". Does this mean I need to add ObjectTag to my WebEntities context? Might there be some other efficient way on joining the two?

Was it helpful?

Solution

You do not split the related entities into different contexts when using EF. The entity classes may reside in different namespaces(projects, etc..) but they should be part of a single context inorder to define a rich model.

It would be better to create a class library project that will contain all the domain entities. This would allow you to declare navigational properties without inter dependent project modules.

The query would be very simple

var recipes = from r in MyEntities.Recipe.Include("Tags") 
              select r 
              where r.Name == "Granny's Meatloaf";

OTHER TIPS

var recipes = (from r in WebEntities.Recipe 
              select r 
              where r.Name == "Granny's Meatloaf").ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top