Why does "linq to sql classes" change the name of a table when making a class? - asp.net-mvc

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!

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.

rename domain class, groovy and grails reverse engineering

How do a rename a domain class while reverse engineering or after reverse engineering.
i generated class using reverse engineering in Groovy and Grails.
the domain class name was AgentTable. I want to rename it as Agent. When i renamed the domain class using IntelliJ (right click - refactor - rename), it renamed the AgentTable to Agent whereever it was used. but when i start the server (run the app), giving error
"nested exception is org.hibernate.HibernateException: Missing table: agent"
I have to do this for few domain class. is it anyway i can give an alternative name while reverse engineering the domain classes.
or after domain class was created how do i rename it without this error.
Look into your database the name of the table it created for the agent. Once you know the name of the table add the following in your new domain
static mapping = {
table "table-name-here"
}
While it works I would not recommend #elixir 's approach.
In my opinion the mapping is not supposed to be used for renames. This is also how I understand the official documentation.
In the example they use it to map Person onto the 'people' table, not because of a rename but because of a semantic reason. Tables are typically named after the plural form. Here is a nice answer on another question regarding this. In the project I am working on the domain object 'User' is mapped to the table 'users'. You can not use the table name 'user' as it is an SQL statement.
Assumptions and clarifications:
In my experience Grails maps the domain name to the table name after these rules (example domain name 'MyExampleDomain':
separate the domain name by capital letters (My Example Domain)
lower case all (my example domain)
replace spaces with underlines (my_example_domain)
Following this your Domain Class 'AgentTable' has a table 'agent_table' in your respective database. After your rename Grails even tells you what it wants:
nested exception is org.hibernate.HibernateException: Missing table: agent
It wants to look up values in a table called 'agent' but it can not find it. The refactor function of IntelliJ does not rename the functions, so it will miss out on the database.
Luckily we know exactly what values it wants - the values previously found in 'agent_table'.
So why create this confusion with remapping domains and table names when we could just rename the table and be done with it?
The solution:
Execute an SQL script like this on your database:
ALTER TABLE <old_domain_name> RENAME TO <new_domain_name>;
The names are of course in their "table-form".
This simply renames your table to match the expected format in Grails. When restarting everything should be fine.
However you do not need to use rename. You could also create a whole new table, build it the way the domain objects wants it to be and then migrate the data. See section 'Problems with this approach' for information on when to use what.
Problems with this approach:
As always, tinkering with information a program depends on (and even generated itself) will often have some dire consequences if you aren't careful.
For example we have to pay attention to keys. If your domain object has a relation to other objects it will hold them in the table via foreign keys. Depending on how you chose to migrate the information in the table you might have deleted these foreign keys connections. You will have to add them via a separate SQL statement. When you choose to recreate the table this will happen for sure. Renaming it should keep the keys.
Another one are column names. If you choose to rename attributes you will also have to rename the columns via SQL. You will also have to remember the foreign keys other tables might have on the table you are renaming. RENAME did this automatically for me, but you should double check.
Why you should still stick with this approach:
Remapping domain objects to the tables with old names is bound to create code smell and confusion. Do you really want to remember these mappings in your head? And more importantly: do you really expect other people to have to work with this?
The best case is if people can't even tell if this object has ever had a different name and changing the database is the best way I know to achieve this.

Entity Framework Multiple EDMX file sharing same tables

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
:):)

Core Data modeler not updating when entity names change

I am having an issue using Core Data modeler. I had an issue where I needed to change the names of entities in the modeler. When I did so, I deleted the associated managed object subclasses, did a clean, then went back the modeler, highlighted the entities with the new names, then generated subclasses using
Editor > Create NSManagedObject Subclass
When I did so, the newly generated subclasses still have the original names. Am I missing something?
In the model editor, you set the class name separately from the entity name. They don't have to be the same. If you only change the entity name name, what you're seeing is normal.
Select the ENTITY you want to change
Select Data Model from right hand top corner as shown below, and change as u want. Entity name and Class no need to be the same.
Finally Clean and Build the project.

EF Database first - Adding new models to existing ones

So I have a database and have created a model from it. Everything works just fine. But now I want to add more tables to my database and produce models from them.
Is that possible with EF Database first? Do I have to recreate all models for it to add new ones? All tables are of course from same database.
Example:
Let's say I have Table1, Table2, and Table3.
And by using DBContextGenerator in VS I've generated models from .edmx file. So I'd have Model1, Model2, and Model3 for corresponding database tables, and I'd like to add Table4 and Model4.
Do I have to recreate everything or is it possible to add somehow?
Open up your .edmx in design view.
Right click in there somewhere and choose "Update Model from Database".
On the "Add" tab, expand "Tables", and find your new database tables.
Check them, and click finish.
I've done this regularly as the DB changes and tables are added during development, it's been very reliable.
To generate the classes, do the following:
Right click on the .tt file of the solution explorer.
Click on the "Run custom tool".
Click on "OK" for the warning.
new classes will be generated.

Resources