简体   繁体   English

修改实体框架模板以在实体属性上包括ReSharper值分析属性

[英]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. 在代码的其他地方,我使用JetBrains.Annotations显示允许使用空值的地方,以及不允许使用空值的地方。 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? 如何使Entity Framework生成包含这些值分析属性的代码?

I'm using Entity Framework 5.0 via the DbContext . 我正在通过DbContext使用Entity Framework 5.0。

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). Solution Explorer中 ,在你.edmx文件会有一个.tt具有相同的名称作为您的EDMX文件(而不是文件.Context.tt一个)。 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. 在第23行附近,您将看到启动新文件的代码。 Modify it to emit a using declaration: 对其进行修改以发出using声明:

    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. 然后,在第73行附近,您将看到一个foreach循环,该循环发出属性代码。 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. 保存文件,您的实体.cs文件将重新生成。 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. 您可能必须添加对JetBrains.Annotations.dll的引用,或者在其他保留这些属性类定义的位置添加引用。

This will put [NotNull] on value types as well which doesn't make sense, but also doesn't cause any problems. 这也将[NotNull]放在值类型上,这没有意义,但也不会引起任何问题。 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. 如果有人对支持模板的模型有更多了解,并且可以建议如何进一步改进它,那么我很想听听它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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