I would like to apply a single transformation over a large number of columns in Entity Framework 5 without having to explicitly type them all out. As an example I would like to do the following over 50+ columns (convert PascalCase to UNDERSCORE_CASE).
modelBuilder.Entity<Department>()
.Property(t => t.DepartmentName)
.HasColumnName("DEPARTMENT_NAME");
I found the Dapper.FluentMap which can provide this functionality but it doesn't appear to work when creating the query.
Is there a way to loop over the list of properties and specify the column name following a pattern? For reference the Dapper Transform is listed as
public PropertyTransformConvention()
{
Properties()
.Configure(c => c.Transform(s => Regex.Replace(input: s, pattern: "([A-Z])([A-Z][a-z])|([a-z0-9])([A-Z])", replacement: "$1$3_$2$4")));
}
EDIT: This is similar to this question but it does not work for me. Perhaps this has different requirements for EF5.
Using the answer from @Hopeless I have attempted the following modification but the syntax is not quite right. I am new to EF so am not familiar with how to convert the older syntax to the newer.
modelBuilder.Entity<Job>()
.Map(m =>
{
m.Properties<Job>(e => e.HasColumnName(name => RegEx.Replace(name, "(?<=.)(?=[A-Z])", "_").ToUpper()));
});
That´s how I solved it. My goal was to have a camelCase convention applied just to an specific table/entity ( Table "Client" ).
You can use the
Properties
method ofDbModelBuilder
. Translate the pascal case pattern to underscore pattern easily like this:The pattern can also be like this
(.)([A-Z])
and the replacement should then be$1_$2
.Of course the input name should exactly have form of
SomeThing
. You can also take the pattern in Dapper (posted in your question), which works more exactly for some other rare cases (even including this formatDDos
(which will be converted toD_Dos
). The point here is it does not translate to uppercase for you.Edit:
It's a pity that in EF5, modelBuilder does not have
Properties()
method. So for a specific entity type, you can try this:NOTE: The code above works only for direct properties, if you have some complex properties (returning some
ComplexType
), then it won't work. Technically you need to exclude all properties (returning ComplexType) from the entity's properties, then if possible merge the properties ofComplexType
with the entity's direct properties before looping through all and configuring each.PS: I'm not sure if Dapper.FluentMap supports EF5, but from the code you posted, it can be as easy as appending the
ToUpper()
method like this:I've tried visiting the homepage of Dapper.FluentMap and looks like that it has some classes based on
Convention
(if this is from EF, it is supported only since EF6). So I'm not sure if the Dapper's code works in EF5. If it works you should try the code above for convenience.