本文介绍了如何通过编辑T4 .tt模板,自动将界面添加到具有特定属性(列名称)的EF数据库第一个生成的实体中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有大约50个数据库,每个数据库有150个表,并且可以使用一个搜索机制来查询具有特定列的表。大多数数据库结构是相同的,所以想法是生成EF实体,并将接口背后生成的实体,如果它们正在生成的表具有特定列,以便稍后可以查询该列。



模型可能会不断变化,所以我无法在表格上手动添加界面 - 这里有T4模板。



我是寻找机制,允许我根据表上的列名添加实体上的接口,从

解决方案

.tt 文件中修改 EntityClassOpening 方法。



stringsToMatch 字典是表上的列名,是要实现生成的接口。

  public string EntityClassOpening(EntityType entity)
{
var stringsToMatch = new Dictionary< stri纳克,串> {{POLICY_NO,IPolicyNumber},{UNIQUE_ID,IUniqueId}};
return string.Format(
CultureInfo.InvariantCulture,
{0} {1} partial class {2} {3} {4},
Accessibility.ForType )
_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);
}

希望这样可以节省你一些时间。


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

解决方案

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.

这篇关于如何通过编辑T4 .tt模板,自动将界面添加到具有特定属性(列名称)的EF数据库第一个生成的实体中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 22:09