Why does EF 5.x use plural name for table? - c#

I've had some experiences in ORM framework such as Hibernate, even Entity Framework 3.0.
By default, those frameworks use singular name for table. For example, class User will map to table User.
But when I migrate to EF 5.x by using Visual Studio 2012, it uses plural name and causes many errors unless I manually map that class by using TableAttribute as:
[Table("User")]
public class User {
// ...
}
Without TableAttribute, if I have a DbContext as below:
public CustomContext : DbContext {
// ...
public DbSet<User> Users { get; set; }
}
Then calling:
var list = db.Users.ToList();
The generated sql looks like:
Select [Extent1].[Username] From [Users] as [Extent1]
Therefore, the error will occur because I don't have any table named Users. Futhermore, I refer to name tables in singular form to plural form. You can see why in this link
I wonder why Microsoft implement EF 5.x that way rather than same to EF 3.0?
Updated:
We can tell EF not use pluralized name by using this code in the context class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
Even if EF tool generates pluralized name, it should keep the mappings to the original database, shouldn't it? Because some users might want to change a few name of fields on their class. EF 3.0 works well, but EF 5.x does not.
Guys, can you give my a reason, please!

That convention is defined in the PluralizingTableNameConvention convention defined by default in the DbModelBuilder.Conventions
If you want to exclude it from all tables, you can use the code from this question.
Why this is done the way it is, I do not know, but I must say that I am, personally, in the camp that thinks that table names should be pluralized :)
Of the example databases provided with an SQL Server instance, Northwind has plurals, and AdventureWorks uses a singular form, so at best, there is no established standard. I've had quite a few discussion for or against each one, but one thing that everybody can agree on is that when once pick a naming strategy, you should stick with it.

When you generate your model with entity framework, uncheck "Pluralize or singularize generated object names"

Related

Entity Framework renaming mistake

I am using Entity Framework Code First in my project, and I did something quite silly I can't fix. I have renamed a table in SQL Server Management Studio, and then deleted it there. I then recreated the correct table (just an 's' that wasn't supposed to be here). Now it's not here anymore and I keep getting exceptions in my queries since EF looks for a table that does not exist anymore (even though I renamed it everywhere!). Now my table is called RelImpUser and it used to be RelImpUsers.
So I have tried recreating the table in SQL Server, then making a migration with :
public override void Down()
{
DropTable("dbo.RelImpUsers");
}
But this does not delete my table. And everytime I execute a query, it looks in RelImpUsers, it does not go for RelImpUser which is the only name I put in my code. Any ideas how to fix this? I can add some code if you want, I just felt it doesn't help much here.
Edit 1: It might have to do with the pluralization of my tables. So all my tables all had plural names, but the new one doesn't, BUT EF still pluralizes because I checked the option when creating DB Code First.
Thanks!
Code First uses its models to build the queries. You will need to annotate your RelImpUser class (or add comparable fluent code):
using System.ComponentModel.DataAnnotations.Schema;
[Table("RelImpUser")]
public class RelImpUser
{
public int RelImpID { get; set; }
public string Field1{ get; set; }
...
}
Fluent equivalent:
modelBuilder.Entity<RelImpUser>().ToTable("RelImpUser");
If you don't want pluralized names, you can turn that convention off:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

EF6 db first pluralize/singularize for table names that contain underscores

I am trying to create a new Entity Data Model (database first) with entity framework 6 using the wizard provided in Visual Studio 2015 Community edition. All my table names are pluralized (ex. mn_Bills). I chose the "Pluralize or singularize generated object names" but this does not singularizes the object names (i.e. the generated class for table mn_Bills is mn_Bills in a mn_Bills.cs file).
I have modified the "Name" and "Entity Set Name" in the Model Browser which resolved only partly the problem. The classes generated are singular, which is good, but the foreign key associations for N to 1 associations are pluralized:
public partial class mn_Bill
{
...
public virtual mn_Clearing mn_Clearings { get; set; }
}
Do you know if there is any workaround for this problem (besides changing the table names)?
I met a similar problem with underscore table names and it seems that the PluralizationService doesn't support underscores.
The answer, it seems, is to override the default service with some of your own code.
I've not done this for a database first edmx solution, because I'm using an alternative code generation engine - but this may be possible to override in the code generation step.
See this answer here:
Entity Framework EDMX - Entity Pluralization Fix
https://blogs.msdn.microsoft.com/efdesign/2008/12/01/pluralization/
Just select "Pluralize or singularize" option in the EDMX wizard.

Take off database table prefix when using ef6 code first from existing database

I have in my database a lot of tables with the prefix "tbl", like tblCustomer, when generates the model using EF6 tool (Add->New Item->Data->ADO.NET Entity Data Model) and selecting Code First from database, EF generates all the Classes with the tbl as a prefix, how to edit the generation templates to take off those prefix?
Rowan Miller explained how to edit those generation templates in this post Customizing ‘Reverse Engineer Code First’ In The EF Power Tools but don't know how to do it with the new consolidated tools in EF 6
You might have an easier time simply changing the names of the classes and using DataAnnotations (look for the section called "Table and Column") to map to the correct tables after you generate your code first models.
using System.ComponentModel.DataAnnotations;
[Table("tblMyModel")]
public class MyModel {
public int ID {get; set;}
//etc
}
Alternatively you can use the FluentAPI as well.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<MyModel>()
.ToTable("tblMyModel");
}
This of course may not be practical for large table structures, but it will work.
If you want to venture into the more advanced options that EF6 offers, you can read up on Code First Conventions.

Can I change the default schema name in entity framework 4.3 code-first?

Currently I am deploying my application to a shared hosting environment and code-first with migrations has been working great except for one minor hiccup. Everytime I want to push the site I have to use the "Update-Database -script" option because I have to prepend every table name with [dbo] because by default the shared host creates a default schema name that is the same name as the database username.
If I log into my shared host and create a database, I then have to create a user. If I name that user admin, then the tables code-first creates while logged in as admin look something like this "[admin].[BlogPosts]". When the application runs all the tables are created but I get an EF exception because it says "[dbo].[BlogPosts]" is invalid. If I rename the table's schema name to "[dbo]" instead of "[admin]" that fixes it.
To get around this I have to generate a migrations script to be executed manually and add "[dbo]" in front of all the table names because the script only references the tables by their name, not by their schema and their name.
Is there an easy way to get around this? It would be so nice if all I had to do was publish the application and everything just worked. If it wasn't for the schema name discrepancy it would be a one click deploy and everything would be glorious.
For those using Entity Framework 6, just use the HasDefaultSchema method:
public class Contexto : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("MyDefaultDbSchema");
}
}
You could use the ToTable method to specify the schema name. If you do not specify the schema name, EF will by convention use dbo.
public class MyContext
{
private string schemaName = "Foo";
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().ToTable("MyTable", schemaName);
}
}
In EF Code first, by default, everything is set up based on user access with a managerial access "DBO-Schema" in the SQL Server. But if a specific user is defined to work with a database that is common in shared hosting, then there will no longer be Dbo management access. This time the names of our tables are dbo.tableName, for example, someUser.tableName, and inaccuracy of this point makes it impossible to run the program. To modify and explicitly assign a user connected to a database. If you use metadata, the following method should be used:
[Table("MyTableName", Schema="MySchemaName")]
public class MyClassName
{
//Other Lines...
}
Or (Whether or not Fluent API is customizable as follows:)
modelBuilder.Entity<Blog>().ToTable("MyTableName", schemaName:"MySchemaName");
Notice the following:
a good reference for study:
http://www.c-sharpcorner.com/article/fluent-api-in-code-first-approach/
For database-first implementations, it's easy. Open the edmx file, right click -> Properties and set the default database schema.
For code-first, this article seems most promising: https://web.archive.org/web/20150210181840/http://devproconnections.com/entity-framework/working-schema-names-entity-framework-code-first-design
I would like to add since this is for C#, I have written one below for VB
Public Class ClientDbContext
Inherits DbContext
Public Property Clients As DbSet(Of Client)
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
modelBuilder.HasDefaultSchema("dbo")
End Sub
End Class

Fluent Nhibernate - How to specify table name

I just started learning Nhibernate and Fluent Nhibernate. I want to specify table name when I create my mapping class.
Entity name in application is "CustomerOrders" but in the oracle database, table name is "CUSTOMER_ORDERS".
I learnt from googling that I can use "WithTable" to specify database table name.
I am not sure how to use it and where as Vs2008 didn't find the method.
Thanks
public class CustomerOrdersMap : IAutoMappingOverride<CustomerOrders>
{
public void Override(AutoMapping<CustomerOrders> mapping)
{
mapping.Table("CUSTOMER_ORDERS");
}
}
WithTable was renamed to Table for the 1.0 release. It was mentioned in the release notes (first bullet point).

Categories

Resources