我正在使用t4模板来搭建控制器。它使用以下代码生成模型相关属性的SelectLists:
<# foreach (var property in relatedProperties.Values) { #>
ViewBag.<#= property.ForeignKeyPropertyNames[0] #> = new SelectList(db.<#= property.EntitySetName #>, "<#= property.PrimaryKeyNames[0] #>", "<#= property.DisplayPropertyName #>");
<# } #>
在脚手架控制器中,结果是像这样的一些行:
ViewBag.id_state = new SelectList(db.states, "id", "state_name");
但我希望它检查相关实体是否包含名为&#34; active&#34;的属性,如果为true,则生成此代码:
ViewBag.id_state = new SelectList(db.states.Where(u => u.active == true), "id", "state_name");
我知道在模板中我可以使用property.TypeName
或property.ShortTypeName
来提取相关实体的名称,但不知道如何使用它来执行我想要的操作。
答案 0 :(得分:0)
您需要访问特定实体的所有属性。如果您还没有它们,则可以使用typeMapper.GetSimpleProperties(entity)
之类的内容。但是,您获得这些属性,搜索属性的存在只是一个问题:
// grab all the properties
var properties = typeMapper.GetSimpleProperties(entity);
// search for specific property
var hasActive = properties.Any(p=> p.Name == "active");
// format your output based on that property
var filter = (hasActive) ? ".Where(u => u.active == true)" : "";
<# foreach (var property in relatedProperties.Values) {#>
ViewBag.<#= property.ForeignKeyPropertyNames[0] #> = new SelectList(db.<#= property.EntitySetName #><#= code.Escape(filter) #>, "<#= property.PrimaryKeyNames[0] #>", "<#= property.DisplayPropertyName #>");
<# } #>
// Or you can put the condition in the foreach statement:
var properties = typeMapper.GetSimpleProperties(entity);
var hasActive = properties.Any(p=> p.Name == "active");
var condition = (hasActive) ? ".Where(u => u.active == true)" : "";
<# foreach (var property in relatedProperties.Values) {
if(hasActive){
#>.<#= property.ForeignKeyPropertyNames[0] #> = new SelectList(db.<#= property.EntitySetName #>, "<#= property.PrimaryKeyNames[0] #>", "<#= property.DisplayPropertyName #>");
<# } else { #>
ViewBag.<#= property.ForeignKeyPropertyNames[0] #> = new SelectList(db.<#= property.EntitySetName #><#= property.PrimaryKeyNames[0] #>, "<#= property.PrimaryKeyNames[0] #>", "<#= property.DisplayPropertyName #>");
<# } #>