简体   繁体   中英

Check if related model contains property

I am using a t4 template to scaffold controller. It generates the SelectLists for the related properties of the model with this code:

<# foreach (var property in relatedProperties.Values) { #>
    ViewBag.<#= property.ForeignKeyPropertyNames[0] #> = new SelectList(db.<#= property.EntitySetName #>, "<#= property.PrimaryKeyNames[0] #>", "<#= property.DisplayPropertyName #>");
<# } #>

In the scaffolded controller, the result is some lines like this one:

ViewBag.id_state = new SelectList(db.states, "id", "state_name");

But I want it to check if the related entity contains a property named "active", and if true, then generates this instead:

ViewBag.id_state = new SelectList(db.states.Where(u => u.active == true), "id", "state_name");

I know in the template I can pull the name of the related entity with property.TypeName or property.ShortTypeName , but no idea how to use it to do what I want.

You need access to all the properties of the specific entity. If you don't already have them, you can use something like typeMapper.GetSimpleProperties(entity) . However you get these properties, searching for the presence of a property is simply a matter of:

// 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 #>");
<# } #>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM