简体   繁体   中英

EF T4 Template - Conditionally emitting custom attributes

I'm using EF 4.1 "database first" on a project. Using the T4 template, I am conditionally decorating my generated properties with attributes for things like Required, DisplayName, MaxLength. In my T4 template, inside the WriteProperty method, I have something like:

var maxLength = edmProperty.TypeUsage.Facets.Where(f => f.Name == "MaxLength").FirstOrDefault();
if (maxLength != null && maxLength.Value.ToString() != "Max")
{#>
    [MaxLength(<#= maxLength.Value #>, ErrorMessage = "<#=edmProperty.Documentation != null ? edmProperty.Documentation.LongDescription : edmProperty.Name #> cannot exceed <#=maxLength.Value #> characters.")]
<#+}

This works great for information that can be inferred from the edmx, but there are some things that are custom and simply not available.

As an example, suppose I want to decorate an EmailAddress property with a custom regular expression-type attribute. How can I "single out" email address fields in my model automatically and apply this attribute without checking the property's name?

Are there ways to "extend" EdmProperty perhaps and add custom properties such as IsEmailAddress?

Thanks!

I think you (kind of) can do that. I have not tried this but I believe if you add an attribute in your namespace to the Edmx file you will be able to access it through metadata properties. Something like this:

<Property Name="ID" Type="Int32" Nullable="false" myNs:regex="xxx" xmlns:myNs="http://tempuri.org" />

Then you could read the value like this (given you have the EdmProperty):

var metadata = edmProperty.MetadataProperties.Single(p => p.Name == "http://tempuri.org:regex");
Console.WriteLine(metadata.Value);

The only problem here is that whenever you update the model from the database the edmx file may be overwritten and you may lose whatever annotations you put in your edmx file.

No, there is nothing. EF model designer still has nothing for extending the model with custom metadata, even for validation. You could try naming conventions of course or reinvent the wheel and add your own metadata file aside, but easier way for now is just write validation attributes and metadata types manually for partial classes.

I would definitely vote for adding this feature in EF.

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