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
.
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:Then, around line 73 you'll see a foreach loop that emits code for properties. Modify it to resemble:
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 toJetBrains.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.