How do I automatically add interfaces to EF database first generated entities that have specific properties (column names) by editing T4 .tt templates

折月煮酒 提交于 2020-01-06 19:27:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!