2

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.

Community
  • 1
  • 1
Mickael Caruso
  • 8,721
  • 11
  • 40
  • 72

1 Answers1

1

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.

Tim
  • 111
  • 1
  • 3
  • Unfortunately, the client specified that the accounts database to be separate from the data, though if I had it my way, they'd all go in the same database. We'll just have to make do with slower nested queries, then. – Mickael Caruso Mar 18 '14 at 02:50