问题
I have a around 50 databases that have 150 tables each and working on a search mechanism that would allow to query the tables that have specific columns. Most database structures are same so idea is to generate EF entities and put interfaces behind the entities generated if tables that they are being generated from have specific columns, so that I could later query then on that column.
Model will likely be constantly changing so I can't manually add interfaces on tables - here come in T4 templates.
I am looking for mechanism that would allow me to add interfaces on Entities based on column names on table they are being generated from
回答1:
In .tt
file modify the EntityClassOpening
method in following way.
stringsToMatch
dictionary key
is column name on table and value
is interface you want to be put on entity generated.
public string EntityClassOpening(EntityType entity)
{
var stringsToMatch = new Dictionary<string,string> { { "POLICY_NO", "IPolicyNumber" }, { "UNIQUE_ID", "IUniqueId" } };
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1}partial class {2}{3}{4}",
Accessibility.ForType(entity),
_code.SpaceAfter(_code.AbstractOption(entity)),
_code.Escape(entity),
_code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)),
stringsToMatch.Any(o => entity.Properties.Any(n => n.Name == o.Key)) ? " : " + string.Join(", ", stringsToMatch.Join(entity.Properties, l => l.Key, r => r.Name, (l,r) => l.Value)) : string.Empty);
}
Hope this saves you some time.
来源:https://stackoverflow.com/questions/37811254/how-do-i-automatically-add-interfaces-to-ef-database-first-generated-entities-th