Reputation: 211
I'm using EF5 Code First, I have entities named XXXEntity
which is based on Entity
class, in Entity
class there is Id
property.
Here is the problem, normaly EF will create table for each entity named XXXEntities and having Id field. What I want is the table should named XXX
(without Entities) and the Id should be XXXId
. How to do that at once by using convention. I know I can override the table name, and Id name one by one. But it is a bit boring and not reusable, is there any better way to do that using convention or something on EF 5?
UPDATE
i read about custom code first conventions but not sure is this an out dated page or a non implemented feature. because i couldn't found the Properties<T>()
method on EF 5
Upvotes: 1
Views: 337
Reputation: 7262
No, you can't do that with EF 5, your link is a future feature for EF 6 see here
but you can do that with reflection easily, for reusability you can make it as an extension method of DbModelBuilder
, a bit slow but it solve your case. here what you can do:
public static class MyCustomNamingConvention
{
public static void ToMyDatabaseNamingConvention(
this DbModelBuilder mb, IEnumerable<Type> entities)
{
foreach (var entity in entities)
{
var mi = typeof(MyCustomNamingConvention)
.GetMethod("MyNamingConvention")
.MakeGenericMethod(entity);
mi.Invoke(null, new object[] { mb });
}
}
public static void MyNamingConvention<T>
(DbModelBuilder mb) where T : Entity
{
var tableName = typeof(T).Name.Replace("Entity", "");
mb.Entity<T>().HasKey(x => x.Id);
mb.Entity<T>().Property(x => x.Id).HasColumnName(tableName + "Id");
mb.Entity<T>().ToTable(tableName);
}
}
Simply use it on your DBContext on OnModelCreating
method
protected override void OnModelCreating(DbModelBuilder mb)
{
base.OnModelCreating(mb);
mb.ToMyDatabaseNamingConvention(GetEntities());
}
Note:
MyCustomNamingConvention
. GetEntities()
is a method to iterate your entity (remember to skip
the Entity
base class)Upvotes: 2
Reputation: 1624
Use this to remove table pluralizing:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
I cant seem to find a convention that you can disabled for the column Id name. Have a look at http://msdn.microsoft.com/en-us/library/gg696316(v=vs.103).aspx
Upvotes: 1