Entity Framework Multiple EDMX file sharing same tables - entity-framework-6

Environment : EF 6, SQL 2012
Setup: Database First, LazyLoading disabled
The question might appear more generic but will try to explain it in the best possible way.
I have a large application using ASP.NET MVC and grouped the entity based on the logical functionality. Hence we built multiple EDMX files
There is scenario in which we have to use the similar entity in two EDMX file.
School has relation to Teachers and Students.In first EDMX file, i used school and Teachers.In Second EDMX file, i used school and students
But only one Entity class getting created. If i run the custom tool on second EDMX context file, then the entity(school.cs) on my first edmx getting disappeared and it appears on the second one..
Why this strange behaviour occurs?
Here is the code in my first EDMX file
As you see here, i m not accessing school entity and also i disabled Lazyloading. But it complains that it couldnt find school file. Note: Courses has navigation property to school. But i didnt include it here.. Why its occuring so?
var courses= DB.courses
.AsNoTracking()
.Select(e =>
new CourseDTO()
{
CourseID= e.CourseID,
Name= e.CourseName,
Desc= e.Desc,
isActive= e.isActive
})
.OrderBy(e => e.CourseID);
The problem is, I m able to include one entity in the EDMX file only..
In first EDMX, it has navigation property to Teachers
In second EDMX , it has navigation property related to Students. But only Entity file exists at a time.. With only one Entity file, the code breaks
Note: This is just sample..Not my original application

Thanks #GertArnold. Meanwhile, i tried to create folders and kept the EDMX file inside it. Means i created seperate folder for each logical group and then included edmx file inside it. This in turn made the edmx file entities have different name space(i mean the entity classes) and also it enabled to have the same entity across multiple EDMX files. It sounds to have resolved my problem.
I didnt try to have them included under different namespace.. The whole idea started when i realized that even though i have two EDMX files, the associated entities(.csfiles) are created in the same physical location. I tried to create sub folders and included the EDMX files. It resolved the problem and i found it is having different name space
:):)

Related

Entity data framework in MVC - recurrent error database-first model update

This is probably the single biggest time-waster I have: I must have wasted cumulative days trying to get round it.
I'm using Visual Studio 2015 and ASP.NET MVC 5, but don't think this is important - I've had this problem in other versions. I accept that it's based on my ignorance.
I've got a reasonably complicated SQL Server database, and am using database-first model generation. To keep things manageable, I've got about 20 different models, each containing tables on a particular theme.
So let's say I want to generate a model to contain tables to do with the maps in my database. First thing to do is to add a new entity model database:
I want to call my model webMap:
I choose to generate the model from my database:
I've got a perfectly good connection string to the database in my web.config file, so I use that and choose not to save this:
I then choose the tables for which I want to generate classes, and these options:
What happens then is that it doesn't recognise the new database context:
The reason is (I think) in this file:
This has created a class named after a connection string:
If I change the partial class and constructor name like this:
then it solves the problem - until I next need to update the database.
Please forgive my ignorance about what's going on. Although I like what entity frameworks do, I find the opacity of what's going on hard to work with. Could any kind person tell me what I'm doing wrong, without delving into T4 transformations? I've tried cleaning my solution and running custom tools, by the way. Thank you!
Open the edmx file in the designer and click somewhere inside to select the conceptual model in the Properties window. Now look at Entity Container Name property. The value should be Entities - I think derived from your connection string name and no way to be specified during the Add wizard steps.
Simply change it to the desired name of the context (like webMap), save/build and you are done.
But make sure the Namespace and Entity Container Name property values are different.
Many thanks to Ivan and garret for their answers. I've collated the information and put here a procedure which worked for me. I don't claim to understand fully what's going on (but surely the point of a framework like this is that I shouldn't need to?).
Here's how I managed to create my model. There are 6 steps. I don't know which of them can be omitted, but following them all solved my problem.
Step 1 - Delete any existing models referencing tblMap
I found that I had inadvertently created another model. Doing a global search for (in my case) webMap can help find if you are in the same position.
Step 2 - clear the web.config file connection strings
I don't understand why, but it appears that the connection strings in your web.config file show up as conflicting names in code. So I did a search for webMap in my web.config file and deleted all connection strings containing it. I think this is the step that I had previously omitted.
Step 3 - Clean and rebuild the solution
I cleaned the solution (no idea if this was necessary), then rebuilt it to ensure that the only errors I had left were in my code referencing the webMap database context which no longer existed.
Step 4 - Follow the steps to add an ADO entity model
But ... call the item name in the first screen something like webMapModel, the connection string something like webMapEntities (and choose to save this in the web.config file) and the namespace something like webMapNamespace. Note that none of these is the webMap name I want to end up with.
Step 5 - Change the entity container name
Double-click on the model .edmx file which has been created to open it (this might not be necessary - it may be open already). Click on the white background of the model to deselect any entities. Press F4 to bring up properties.
Change the entity container name to webMap as shown above.
Step 6 - Rebuild your solution
At this point all my errors disappeared!
Name of Your context, should be different than namespace.
Try to use this configuration:
And in next screen:
And yes, it will add next connection string to web.config, but it's ok.

Code First and Model First in the same project?

I have two databases that I am accessing. The first is against a contact database which I connected to using EF Model First; creating the edmx. I have since begun to learn the virtue of CODE First when working with Entity Framework, so I decided I would, in the same project, write the Product database using Code First techniques, allowing the database to be generated from the code I am writing.
Everything compiles fine. The problem occurs when I hit my harness and it attempts to create the Product database and retreive a list of values from one of the tables...
I get the folowing error "Could not find the conceptual model type for 'Core.Data.Account'", when I attempt to enumerate the ProductLines property (Line3 below).
1. using (var ctx = new ProductDb())
2. {
3. var lines = ctx.ProductLines.ToList();
4. this.litOne.Text = lines.Count.ToString();
5. }
After some research it appears that this message may be occuring because of multiple entities with the same name (regardless of namespace), however there is nothing in the ProductDb context with the name "Account".
There is a class in the OTHER context created by the Model First approach named "Account". But how/why would that make a difference? They each point to different databases i.e. different connection strings. Why would the ProductDb be attempting to create a table called Account, when it should be completely unaware of it's exstence?
thoughts?
Thank you as always!,
- G
I bumped into the same problem, but the other way around: first a DbContext + generated database and then generated an edmx off the database (just for a little presentation). It appeared to be a restriction in EF: EF currently has a restriction that POCO classes can't be loaded from an assembly that contains classes with the EF attributes.
The only thing you can do for now is keep the contexts in separate assemblies.

HOw can I access two database in single .edmx file?

I have created mvc3 application.
I have one .edmx already created which is based on Db1 but now
I have created a view which is based on Database2 and I need to use this view inside my project.
For that I need to update my EF .edmx file.
but when I right click and select option Update model from Database
i'm only getting all tables , view ,sps fromDb1` its obvious
But as i need to use view which is fromDatabase2how can i add it into my model.edmx` file?
please help.
If two edmx want to merge then make partial class same for both edmx file (there will be two designer classes). Add another constructor and make it parametrized, for other edmx file. Parameter to identify which edmx want to load.
Add another class file in Business layer create object of edmx partial class in this class file, Under this class when ever you want to load whom so ever edmx file pass some argument in constructor of edmx partial class constructor to identify which connection needs to open.
Pass parameter in constructor of edmx designer class, based on decided page name (custom logic or table name; That edmx will get loaded.
In web config file multiple connection strings will available for multiple edmx file.
Entity Framework does not support mapping more than one database to one model/.edmx file (see See : unify two models (edmx) with visual studio 2010)
So you'd need to create a separate .edmx file/model for the other database, and reference each model with separate contexts. You'll need 2 connection strings in your projects as well.
One "hack" might be, for i.e. MS SQL to link these two servers and expose the data from other one on first one, i.e. via view. But I think it's manageable only for few tables. With huge models this will be pain. Other databases (Firebird, Oracle, ...) support this in similar way.
What I have done , created stored procedure in db A and accessed the db B through that SP , say select * from db2.table.then create a function import for that particular SP .
This approach works well if you have both databases on same server. In case these are on different servers you can create Linked Server on B to access A using the same stored procedure approach.
Using ctx As New Entity()
ctx.Database.Connection.ConnectionString = conString
End Using

+entityForName: could not locate an entity named 'Dogs' in this model.

A little question regarding Core data models.
Here is why I'm posting : +entityForName: could not locate an entity named 'Dogs' in this model.
What I wanna do :
I wanna create an app that will read/write in core data details about animals with 2 entities Cats and Dogs.
-For that I create a window-based project with "use core data" checked.
-Then I create my views, and click on "animals.xcdatamodeld" file to create a first entity called Cats. I add the attributes, generate the class "cats.h" and "cats.m".
- I write down the code to read and write on this entity => No problem everything works well.
At this point I made a mistake by deleting the file "animals.xcdatamodeld" manually... I recreate it with the same name and add a new entity Dogs with its attributes and generate the associated class.
That's where the problem is, when I build and run the error message comes : +entityForName: could not locate an entity named 'Dogs' in this model. FYI, the read/write on Cats is still ok.
I have no idea why this error appears... I did not change anything on the App Delegate. I found very little information online related to that issue.
This only thing I found was that maybe the model needs to be versioned when updated => Can someone explain that a lil bit please ?
Anyway the model does not seem to have been updated when I added the new entity...
Thx.
Ok as expected somehow, this error was due to a stupid mistake...
The deleted xcdatamodeld file was replaced by a new one with a different spelling...
Now everything's fine...

Why does "linq to sql classes" change the name of a table when making a class?

I go in and add a new "linq to sql classes" in Visual Studio and then go and drag a table from Database Explorer to the new DBML and the name of the new class is no longer plural. What if I still want it to be plural? If I drag a table that isn't plural I get a bunch of compile errors about how there is already a type definition for all of the fields in the table I put on the dbml layout. If I then make the class name plural for the table that wasn't plural in the dbml layout by clicking on the name and changing it then no more compile errors.
You can single click on the tablename in the dbml table and rename it. Or you can select the table in the DBML and go to the properties window. There you can change the name, and the table it hooks up to.
One way to avoid the name conflict is to designate namespaces accordingly. For example, you can place your DBML file in a subfolder in your project and assign it something like DataAccess. Therefore, when you map to the Ling2Sql class, you'd do DataAccess.Customer and you can avoid the conflict with Customer, since it lives somewhere else.
As a tidbit, Linq2Sql by default makes tables non-plural. It's based off of a convention. For example, a table Customers has many customers. When you instantiate an object, you're looking at a single Customer, not the table. The object is essentially being mapped to a row in the Customers table, thus it becomes singular.
I just figured out what was happening. After the "move it to a new folder" suggestion I tried that and it worked. But it didn't make any sense as to why it worked because if there were type conflicts there should have still been the same conflicts in the new folder but I had none of the problems I was having before and I could rename things anything I wanted after moving to a new folder and there were no conflicts. Renaming things after dragging it over is a bad idea because if the database schema changes and you want to update your classes you have to drag the table back over and then make the changes manually again.
ANYWAY, the problem is that before I made the "linq to sql classes" I made a "ADO.NET Entity Data Model". That's what was causing all the name conflicts. But the suggestion about moving it to a new folder was awesome and led me to the final solution!

Resources