ef 核心忽略导航 属性

ef core ignore navigation property

我有一个实体 User,它有两个属性 CreatedByUpdatedBy,都引用 User。默认情况下,EF 假定这两者是一对一的关系。我收到以下错误消息:

Message: System.InvalidOperationException : The child/dependent side could not be determined for the one-to-one relationship that was detected between 'User.CreatedBy' and 'User.UpdatedBy'. To identify the child/dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship configure them without specifying the inverse. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.

目前,我有一个 class 这样的:

public class User
{

    public int Id { get; set; }

    public int? CreatedById { get; set; }
    public User CreatedBy { get; set; }

    public int? UpdatedById { get; set; }
    public User UpdatedBy { get; set; }

}

基本上,这就是我正在尝试的:

如何让 EF 忽略导航 属性?我有 CreatedBy 的主要原因是我以后可以使用 Include(u => u.CreatedBy)。我知道使用 IEnumerable<User> AllCreatedUsers 属性 可以解决这个问题,但我不想为我的实体中的每个创建一个 IEnumerable。有没有办法用流利的 API 做到这一点?

这是我尝试过的:

modelBuilder.Entity<User>()
                .Property<IEnumerable<User>>("AllCreatedUsers");

modelBuilder.Entity<User>().HasOne(u => u.CreatedBy)
                                .WithMany(u => EF.Property<IEnumerable<User>>(u, "AllCreatedUsers"));

您需要使用无参数 WithMany 方法重载配置两个 Single Navigation Property 关系:

modelBuilder.Entity<User>()
    .HasOne(u => u.CreatedBy)
    .WithMany();

modelBuilder.Entity<User>()
    .HasOne(u => u.UpdatedBy)
    .WithMany(); 

ForeignKey 两个属性的数据注释。

public class User
{
    public int Id { get; set; }

    public int? CreatedById { get; set; }
    [ForeignKey("CreatedById")]
    public User CreatedBy { get; set; }

    public int? UpdatedById { get; set; }
    [ForeignKey("UpdatedById")]
    public User UpdatedBy { get; set; }
}