Using two different databases simultaneously using Entity Framework - entity-framework-4

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.

Related

asp.net mvc load related data from multiple contexts

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.

MVC 4 + Entity Framework 5 + Stored Procedures

I'm just now teaching myself MVC4 (did webform for years), and I'm
frustrated - but not about MVC which is pretty good. Entity Framework
is...well
I'm using VS2010.
The problem
We have a real database, you know normalized with like foreign keys and stuff. But every example I find for Entity Framework is direct to the table, but we rarely have a straight table pull - out side of populating dropdowns and such. All of our frontend calls hit a Stored Proc (how old school! expletive deleted)
I love the Model architecture of MVC where you define the attributes of the data coming from the data source - Display Name, Ranges, DataType. etc. So I definitely want to keep this.
Entity Framework and MVC do not want to play well in this senario. I created my edmx file (with SPs only), did my function import for a SP, everything is good....'til now.
Can't Create a Controller from the edmx/designer - Enter Controller Name, pick MVC controller with read using EF, pick the model class that is the FuntionName_Result, and for context pick the ...Entities name. FAIL Unable to retrieve metadata
OK, so now I try EF 5.x DbContext Generator, update the file name and boom I have a model and context - awesome now I can do the cool MVC stuff, lets rebuild the site....oh the horror - everything has been previously defined.
I tried generating the edmx in a different folder and/or deleting it after the DBContext generator, still can't create Controller.
'blah' is not part of the specified 'Context' class, and the 'Context' class could not be modifed to add a 'DbSet' property to it. (For example, the 'Context' class might be in a compiled assembly.)
IF I manually add the DBSet, I'm back to unable to retreive metadata - I am assuming this is happening because it can't connect to the DB. I don't know where to tell it to use the connection string in web.config. - if this is the problem
Here lies dead my MVC hopes of a brighter future.
What am I missing?
I am not married to EF, so if there is a better way to access databases (without writing all the code from scratch) I'm here to listen.
Thanks
Entity framework relies heavily on conventions. It takes a little bit to get used to. For example for connection strings... If entity framework doesn't find a connection string with the same name as your DBcontext class it just makes one (i think it defaults to using the project name as the database name). If this database doesn't exist it will create it locally as a sql express DB. This leads to the kinds of errors like the ones you are reporting.
If you want to define the connection string for entity framework all you need to do is provide a connection string in the web.config. Again conventions.... the connection string should be named the same as your DBContext class and entity framework will just find it.
<connectionStrings>
<add name="MyDbContextClassName" connectionString="..." />
</connectionStrings>
On an architecture note, IMHO ORM's are defiantly the way to go for new application development. It makes getting data into and out of your database soo much easier. That said it is a Big paradigm shift if you are used to accessing everything via sprocs and direct queries to the DB. Don't give up on it. It will frustrate you at first just like picking up any new tech, but it's well worth it in the end.
I have used entity framework and nHibernate for ORM in the past. The thing that I like about entity framework is that if you use code first migration most of the really annoying, tedious, and error prone column mappings are auto generated for you (again using conventions). You sometimes still end up having to do a little mapping but those cases are pretty rare. Maybe a little less rare if you already have a database since your column names will probably not always match entity frameworks conventions. Anyway... This is a big plus in my book and why I would defiantly favor EF over nHibernate.
If you already have a database, with stored procedures you do not need the EF 5.X DbContext Generator. Create either a folder in your project or a new project in your solution for your data access. In that folder/project add a edmx file and configure it to an existing database using the wizard. At this stage you can pull in your stored procedures.
If you open the edmx file, you can go to the model explorer tab and manage the imported functions (stored procs) and their return types.
Once you have that, In your controller, rather than using an instance of DbContext you can just use an instance of your EF Entities. So if you called your edmx 'MyDbAccess' you should be able to use MyDbAccessEntities which will then allow you to access the stored procedures.
I in your App.config file check your
<connectionStrings>
After check if your stored procedures are added in the model context file
YouDBModel.Context.tt
> YourBDModel.Context.cs

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.

EF4 and ASP.Net MVC to Test and Develop without mapping to an underlying database (until later)

I want to develop an ASP.Net MVC application with EF4 Model First design and only generate the actual database much later, ideally at the end of the project.
Based on some of the ideas here:
http://elegantcode.com/2009/12/15/entity-framework-ef4-generic-repository-and-unit-of-work-prototype/
I want to create something like an InMemoryObjectContext for testing and development and use IOC to switch to the SQL Server implamentation (EF generated) for UAT and production.
Is this wise?
Is it possible? If so, does anyone have any suggestions?
Does EF always need an underlying database in order to track changes, commit etc?
I've tried creating a model first but as soon as I add properties I get the following errors:
Error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer Model1Container.
and the warning:
Running transformation: Please overwrite the replacement token '$edmxInputFile$' with the actual name of the .edmx file you would like to generate from.
The error doesn't stop the application running but worries me. I'm very very new to EF so I apologize if this is way off the mark or a dumb question. I'm hoping to get some good advice while I sit for the next few days and watch videos and read articles.
Thanks
Davy
At the very least you need mapping information "filled in". You can fill these fields with nonsense if you don't want to work against the underlying database.
If your doing Model first, right click on the designer canvas and select, "Generate Database from Model". This will automatically create convention based mappings for you without defining tables and columns. You don't even need a valid db connection to do this.

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