问题
I'm hoping to set up an EF Code First convention where all of the column names of the properties have a lowercase first letter.
However, I have other fluent API code that changes column names from the default. I can't seem to find a way to get access to the current column name of a property in order to lowercase the first letter. Starting with the PropertyInfo, as in modelBuilder.Properties() is not enough because the column name may have already been set to be different than the member name.
How do I generically tell EF Code First to lowercase the first letter of all column names?
回答1:
OK, the DBA's are speaking. Let's bow our heads in reverence and see what we can do. I'm afraid that in EF 5 (and lower) there's not much you can do to make it easy. In EF 6 there is this feature of Custom Code First Conventions which actually make it a piece of cake. I just tried a small sample:
// Just some POCO
class Person
{
public int PersonId { get; set; }
public string PersonName { get; set; }
}
// A custom convention.
class FirstCharLowerCaseConvention : IStoreModelConvention<EdmProperty>
{
public void Apply(EdmProperty property, DbModel model)
{
property.Name = property.Name.Substring(0, 1).ToLower()
+ property.Name.Substring(1);
}
}
class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>();
// Add the convention to the modelbuilder.
modelBuilder.Conventions.Add(new FirstCharLowerCaseConvention());
base.OnModelCreating(modelBuilder);
}
}
After running
using (var db = new MyContext())
{
db.Database.Create();
}
my database has a People
table with personId
and personName
.
And some simple CRUD actions work flawlessly:
using (var db = new MyContext())
{
var p = new Person { PersonName = "Another Geek" };
db.Set<Person>().Add(p);
db.SaveChanges();
}
using (var db = new MyContext())
{
var x = db.Set<Person>().ToList();
}
So if the DBA's want their conventions, you can demand a new toy :)
来源:https://stackoverflow.com/questions/15160212/ef-code-first-fluent-api-lowercase-first-letters-of-all-columns