【问题标题】:Entity Framework Core 5.0 Reference Navigation RequiredAttribute + Migration not workingEntity Framework Core 5.0 参考导航RequiredAttribute + Migration 不起作用
【发布时间】:2021-03-07 20:26:11
【问题描述】:

我们最近刚刚将一个 ASP.NET Core 项目升级到 5.0,并提供所有可用的 Entity Framework (nuget) 升级 - 将其全部升级到最新的 5.0 版本。

在创建新迁移时,似乎带有[Required] 属性的引用导航属性不再导致迁移将列创建为NOT NULL

我们的代码(注意Template 引用导航属性):

/// <summary>
/// A document is a completed template
/// </summary>
public class Document
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int? Id { get; set; }
    [Required]
    public string Name { get; set; }

    public int CompanyRecId { get; set; }
    public int AgreementRecId { get; set; }
    /// <summary>
    /// A HistoryId is common to all documents copied from an original document.
    /// Thus;
    /// - A document is created via a template
    /// - A second document is created by the original document.
    /// - The two documents are linked by the same GroupId.
    /// </summary>
    [Required]
    public Guid HistoryId { get; set; }
    [Required]
    public string Creator { get; set; }
    [Required]
    public DateTime Created { get; set; }
    [Required]
    public virtual Template Template { get; set; }

...构造函数,方法如下

创建迁移时(例如Add-Migration Update17),会生成以下(Up)代码:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_Documents_Templates_TemplateId",
            table: "Documents");

        migrationBuilder.AlterColumn<int>(
            name: "TemplateId",
            table: "Documents",
            type: "int",
            nullable: true,
            oldClrType: typeof(int),
            oldType: "int");

        migrationBuilder.AddForeignKey(
            name: "FK_Documents_Templates_TemplateId",
            table: "Documents",
            column: "TemplateId",
            principalTable: "Templates",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    }

TemplateId 列正在从以前的 nullable: false 更改为 nullable: true - 我的问题是为什么?

我已阅读重大更改文档here 和关系文档here,这似乎表明功能已更改,但在此特定情况下似乎没有? 添加带有 RequiredAttributeTemplateId 属性 (int?) 时 - 迁移按预期进行,TemplateId 列上没有任何变化。

我似乎遗漏了什么或没有清楚地理解文档 - 任何帮助将不胜感激!

【问题讨论】:

  • 这听起来像是一个错误,请考虑将其发布到他们的 GitHub 问题跟踪器。

标签: .net-core entity-framework-core ef-code-first entity-framework-migrations


【解决方案1】:

为了解决这个问题,我在 Template 类上添加了一个属性 -

public virtual List<Document> Documents { get; set ; }

这似乎为 EF 工具提供了检测 RequiredAttribute 并正确构建迁移所需的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2020-08-11
    • 2023-03-14
    • 1970-01-01
    • 2021-06-13
    • 2019-03-12
    • 1970-01-01
    • 2017-09-30
    相关资源
    最近更新 更多