DataAnnotations 或流利的 EF Code First 自我评价 API

EF Code First self rating by DataAnnotations or fluent API

我有一个class:

[Table(nameof(User), Schema = "Administration")]
public class User : IBaseModel
{
    [Key]
    public int UserId { get; set; }

    #region IBaseModel

    public int AddedBy { get; set; }
    [ForeignKey("AddedBy")]
    public virtual User UserAddedBy { get; set; }

    public int ModifiedBy { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User UserModifiedBy { get; set; }

    #endregion
}

我尝试为此 table 创建自我关系(谁添加了谁和谁修改了项目)

当我的 class 看起来像上面并且我尝试在程序包管理器控制台上使用 Add-Migration init 时它 returns 错误:

Unable to determine the principal end of an association between the types 'abc.Administration.User' and 'abc.Administration.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

出现此错误后,我尝试使用流利的 API 和方法 OnModelCreating(在我的上下文中)我写道:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserAddedBy).WithMany().HasForeignKey(m => m.AddedBy);
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserModifiedBy).WithMany().HasForeignKey(m => m.ModifiedBy);
    }

再次尝试 Add-Migration init 但我再次看到错误消息:

One or more validation errors were detected during model generation:

abc.User_UserAddedBy: : Multiplicity conflicts with the referential constraint in Role 'User_UserAddedBy_Target' in relationship 'User_UserAddedBy'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. abc.User_UserModifiedBy: : Multiplicity conflicts with the referential constraint in Role 'User_UserModifiedBy_Target' in relationship 'User_UserModifiedBy'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

我找到了在虚拟属性之前向属性添加 Required 的信息,但没有帮助。

Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

尝试使用 int? 而不是 int

根据提供的说明,您可以执行以下操作:

  1. 禁用强制执行外键 (FK)
  2. 添加一个虚拟用户,你可以使用像 "System" 这样的名称,给它一个像 -1 这样不可能的 ID。
  3. 让系统成为它自己的 UserAddedBy 和 UserModifiedBy
  4. 启用强制 FK。 现在您可以添加具有系统的用户作为他们的 UserModifiedBy 和 UserAddedBy。

这样,用户中唯一的 "cheated" 将是系统,在我看来,这是一个不错的权衡。