.netentity-frameworkresharperdbcontextvalue-analysis

Modify Entity Framework template to include ReSharper value analysis attributes on entity properties


My entity data model contains information about what fields are nullable and non-nullable. However, the generated templates do not include this information.

Elsewhere in my code, I use JetBrains.Annotations to show where null values are permitted, and where they are not. For example:

[NotNull]
public string Thing([CanBeNull] string s)
{
    return s ?? "Was null";
}

How can I make Entity Framework generate code that includes these value analysis attributes?

I'm using Entity Framework 5.0 via the DbContext.


Solution

  • In Solution Explorer, under your .edmx file there will be a .tt file with the same name as your EDMX file (not the .Context.tt one). Open this file for editing.

    This file is a template that is used to generate the entity class source files. We will modify the template to include these attributes in the generated source code.

    Around line 23 you will see code that starts a new file. Modify it to emit a using declaration:

        fileManager.StartNewFile(entity.Name + ".cs");
    #>
    using JetBrains.Annotations;
    
    <#
        BeginNamespace(code);
    

    Then, around line 73 you'll see a foreach loop that emits code for properties. Modify it to resemble:

            foreach (var edmProperty in simpleProperties)
            {
                if (edmProperty.TypeUsage.Facets["Nullable"].Value.ToString() == "False")
                {
    #>
        [NotNull]
    <#
                }
                else
                {
    #>
        [CanBeNull]
    <#
                }
    #>
        <#=codeStringGenerator.Property(edmProperty)#>
    <#
            }
    

    Save the file and your entity .cs files will be regenerated. Open them up to check that they compile correctly. You may have to add a reference to JetBrains.Annotations.dll or wherever else you keep these attribute class definitions.

    This will put [NotNull] on value types as well which doesn't make sense, but also doesn't cause any problems. If someone knows more about the model backing the templates and can suggest how to improve this further, I'd be interested to hear about it.