Entity Framework code with custom property characteristics

custom-attributes entity-framework

Question

Is it possible to include unique characteristics in EF produced code for properties? The only thing that I can think of as a workable approach is to create a unique T4 template. However, it would be difficult to infer the relevant attribute parameter according to an EF property given the attribute's type.

1
26
6/26/2009 7:07:50 PM

Accepted Answer

A metadata type that replicates the characteristics and is only used for attribution might be specified to achieve this.

[MetadataType(typeof(Dinner_Validation))] 
public partial class Dinner 
{} 

public class Dinner_Validation 
{ 
    [Required] 
    public string Title { get; set; } 
}

About it, Steve Smith blogs at here.

Unfortunately, the aforementioned method is difficult to modify. The new POCO entities are a different choice. I believe they completely eliminate compile-time code creation. Since I haven't utilized them yet, I can't speak to any potential drawbacks or trade-offs.

35
8/18/2010 9:01:02 PM

Popular Answer

This may be included in the EDMX file, along with Designer:

<Property Name="Nome" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" >
            <Documentation>
              <Summary>[MyCustomAttribute]</Summary>
            </Documentation>
</Property>

and swap out T4:

void WriteProperty(CodeGenerationTools code, EdmProperty edmProperty)
{
    WriteProperty(Accessibility.ForProperty(edmProperty),
                  code.Escape(edmProperty.TypeUsage),
                  code.Escape(edmProperty),
                  code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
                  code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}

With:

void WriteProperty(CodeGenerationTools code, EdmProperty edmProperty)
{
    if(edmProperty.Documentation != null && string.IsNullOrWhiteSpace(edmProperty.Documentation.Summary) == false)
    {
    #>
    <#=edmProperty.Documentation.Summary#>
<#+
    }
    WriteProperty(Accessibility.ForProperty(edmProperty),
                  code.Escape(edmProperty.TypeUsage),
                  code.Escape(edmProperty),
                  code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
                  code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow