Mickael Caruso
Mickael Caruso

Reputation: 9441

Entity Framework - "Navigation Property" In A Different Data Context?

Note that someone asked a similar question and I don't feel that it was answered - Entity Framework Code First, Navigation Property between different contexts/databases

I have an AccountsDbContext and a DataDbContext. For DataDbContext, I created a class:

public class Article
{
    public int Id { get; set; }
    public string Title { get; set; }
    // Other data properties not shown for brevity.

    public string UserId { get; set; } // who wrote/owns this article?

    [ForeignKey("UserId")] 
    public virtual IdentityUser User;
    /* I don't think I can do the above because IdentityUser is another context -
       AccountsDbContext.
    */
}

I'm thinking of removing the foreign key attribute (or maybe the virtual keyword as well). This would probably lead to a null property whenever Article is accessed, correct? If so, then I would have to perform another query to get the User.

This would be a problem if the user needs to search articles (for example) by the writer's roles, which are part of AccountsDbContext. I would have to grab all results first, query the user info for each result, then filter. That seems rather slow and would definitely be a waste of computation with pagination.

Is there a better way to handle this situation? Again, we're going by the assumption that we can't foreign-key across data contexts.

Upvotes: 2

Views: 1171

Answers (1)

Tim
Tim

Reputation: 111

There are a couple of theories when it comes to multiple contexts. The biggest issue as you are seeing is that you cannot merge the data between them.

One question that I have is do you need to have multiple contexts? If not, I would use a single context and then the issue would be resolved. Otherwise, as you have stated you would have to get a list of users then filter articles by looping through the users. This over time might get really slow.

Another option you might have is a view-only model in one of the contexts then you could call the appropriate context for full details. This might be a bit cumbersome to maintain.

Upvotes: 1

Related Questions