asp.net mvc load related data from multiple contexts - asp.net-mvc

I have a MVC .Net Core 3.1 project with 2 contexts. One is the standard Identity context and the other is the application context.
These are stored as 2 separate databases on the server.
In my application I have an entity 'Project' and it has a field 'ProjectLeadUserId' in which I store the ID of that user from AspNetUsers.
When I list all of the open projects I would like to show the 'UserName' from AspNetUsers, rather than the GUID related to each of the projects.
Normally I would have a foreign key between the two so that in my view I could do something like:
project.ProjectLead.UserName
But I cant workout how to set that up in my entity as the FK would be in a different context.
Is this possible, or have I caused myself an issue by separating the Identity and application contexts?
Edit:
Ignoring the foreign key issue as I can deal with that in the application logic. Is there a way to load the related data when multiple contexts are involved.
e.g. When I get a list of projects, can I load the related AspNetUsers data, using the AspNetUsers.Id and Project.ProjectLeadUserId?

Quoting from SQL Server documentation:
FOREIGN KEY constraints can reference only tables within the same database on the same server. Cross-database referential integrity must be implemented through triggers. For more information, see CREATE TRIGGER.
It's not possible for you to have a foreign key across different databases in SQL Server.
If the 2 contexts targeted the same DB, I think what you want would still not be possible.
In my past projects I've usually seen people extending the IdentityDbContext to create their DB context and using only that.

Related

Should identity and other app data use the same context

The Users in my database will be related to many other entities. Is the recommended practice for doing this to have 1 db context for the app? Or, should there be two different ones. It seems that I could retrieve the context through the use of the GetOwinContext()
The standard practice with this is to keep all of your tables for your webapp in 1 database (1 context). One large advantage of this is that you can execute SQL joins based on data that is stored in your Identity tables.
Here is a use case: I have a fileupload entity and table which I need to relate to a specific user (the user that uploaded the file). If everything lives in one database then I can use foreign keys and entity framework navigation properties as I normally would. If I was using a separate database/context for the Identity provided tables, then I would need to query two different database (which is more costly performance-wise) to get my needed data. One query to DB1 to get my user Id and another query to DB2 to get the fileuploads which belong to this user Id
So in short, if you have users related to many other entities (which you mentioned) then I would strongly recommend using 1 database and context.

Handling foreign keys in multiple contexts/domains using Entity Framework Code First and Migrations

I'm building a new system that utilizes data from an existing legacy system. A requirement is for our application to use the same physical database but a different schema for isolation. Our application will need read access only from the dbo schema, but our new structure will have foreign keys from the dbo schema so we'll need to enforce that.
I'm planning on creating two different projects with two different contexts. This will facilitate using Reverse Engineer Code First from EF Power Tools on the dbo schema, and using EF Migrations on our new schema. However, I'm unsure how this approach will handle Foreign Keys across contexts/domains. How would I map these so Migrations interprets it correctly?
If you use different schemas and\or different contexts, that means this data can be stored anywhere, even at different storages (files, azure, services). You should not use explicit foregin keys across across contexts/domains. You have to make separate queries to each contexts.
If you really need to do that, you can use databse VIEWS with any joins you need (even from other server). Then just map our EF entity to view:
[Table("MyView")]
public class MyEntity {...}
Obviously, it will read-only entity.

Entity split in two databases

I'm working on a project already started by several developers before me. One thing in particular bothers me is that they have single entity split in two databases.
Entity is called Tracker.
First database is called ConfigBase, and it has table named Trackers that has TrackerId along with it's attributes.
Second database is called StoreBase, and it also has table named Trackers, whose elements have matching TrackerId as it is in the first base.
Moreover, to have things even more complicated, when you access specific tracker in ConfigBase, you gain SQL server name and credentials that allow you to access it in StoreBase.
Now all this isn't too much complicated if you use plain old ADO.NET. But as my task is to raise entire solution to newest EF 4.3.1, I'm having troubles maintaining consistency of my entity. Half of things related to Tracker entity are in ConfigBase and the other half in StoreBase, and usually I have to get both to get some result.
Is there any solution to this that does not involve virtual merge on database level. I'm looking for a solution that can be done with Code First modelling.
Thanks in advance!
No there is no solution provided out of the box because EF itself is even not able to use more than one database per context. So you will either merge your databases or you will access each database separately (with separate Tracker entity per database) and merge data somehow in your application.

Using two different databases simultaneously using Entity Framework

I'm using Entity Framework 4 in an MVC3 project. I'm trying to access two different databases (A and B):
Databases A and B are completely different and unrelated.
Database A is a 'code first' SQL compact database.
Database B is a 'database first' SQL Server database.
I have straightforward queries on either database, no linking or cross-database joins.
Either database connection works if I remove the other DbContext from the project.
Now, when I try to query from database A, I'm getting an Exception "Could not find the conceptual model type for ".
I can't imagine that EF doesn't let you use different databases, so my question is: do I need to do something extra when creating a new instance of the appropriate DbContext, in order for this to work?
I stumbled across this thread while trying to resolve the "Could not find the conceptual model type for" exception.
I am using EF 4.2 with multiple models. I implemented DbContext with one of my models to "try it out". When I compiled and ran, I received the exception above for an entity in a completely different model on a completely different database!
After much hassle I finally implemented DbContext to the other two models and everything ran fine.
I know this doesn't necessarily answer the question, but I wanted to leave this here for anyone else that has the same issue and stumbles across this post.
Make sure you don't use the same entities name for both edmx files. You can change it manully opening a edmx with xml editor right clicking the file and open with.
Note that for some security reasons you can't nest the contexts. They can only be used separated.

EF4 cross database relationships

I was wondering if EF4 support cross-databse relationships? For instance:
db1
Author
Id
Name
db2
Posts
Id
Content
db1.Author.Id
What ideally I need to do to get this relation in my ef4 model?
Do you guys have any idea?
Thanks
I've found this entry in Microsoft Connect that answers the question about the support given at this moment by EF (actually it is not supported yet).
Also found a thread in Social MSDN about this concern.
Other links on Stack Overflow:
ADO.Net Entity Framework across multiple databases
Entity framework 4 and multiple database
In summary, the only given alternatives are:
Using views in EF
Use NHibernate instead
If your database supports Synonyms, you can trick EF to span multiple databases. I wrote up how to do it here.
Basically you end up with an edmx file per database, and a script which merges them into a single edmx file. Synonyms are used to reference one database from another by using the actual table name, so EF doesn't throw a fit when you try to access database2.table from database1. You still have to setup links between the two databases manually in the EF model, but once setup they'll stay even if you re-run the merge script.
Scripts to setup Synonyms and to merge the edmx files are posted in the link
I recently began a project that uses entity framework with two databases, one Oracle and one SQL Server. I could not find any information regarding cross-database or multiple database support in the entity framework.
Most posts from the MS Entity framework team are a couple of years old and indicate that including two databases in a single model is not a feature that will be included soon. I would be interested in having a concrete answer on whether it was included in 2010 myself although I suspect the answer is no.
Currently out project gets around this limitation by having a separate entity model for each database. This has solved the problem for the majority of the scenarios we've encountered thus far in the project.
In cases where we've needed to query the data from the two databases at the same time, we simply created a view in one or the other databases. Since we're using Oracle and SQL Server, this view would utilize either a Linked Server (SQL) or a DBLink (Oracle).
The disadvantage of views in the entity framework is we've had to spent more time than I expected getting the primary keys working.
Hope this helps.

Resources