gpt4 book ai didi

asp.net - 无法将第二个自引用 FK 添加到模型,导致无法确定主体结束错误

转载 作者:行者123 更新时间:2023-12-04 21:10:30 25 4
gpt4 key购买 nike

首先,我知道有很多关于 Unable to determine the principal end of an association between the types 的帖子。错误,但我看到的任何一个都与我的问题不符,如果我错过了一个对不起。

我已经构建了一个实体,它最终会引用它的自身两次,当我将代码放入第一个自我引用时,它工作正常,只要添加第二个它的代码就会中断。做一些测试我发现如果我使用他们自己的任何一个自我引用,一切都很好,只有当我添加第二个自我引用时它才会中断。我用于自我引用的代码是:

    [ForeignKey("ManagerID")]
public User Manager { get; set; }

//Auditing Fields
public DateTime DateCreated { get; set; }
public int? UpdatedByUserID { get; set; }
public DateTime? DateUpdated { get; set; }
public DateTime LastAutoUpdate { get; set; }

[ForeignKey("UpdatedByUserID")]
public User UpdatedByUser { get; set; }

完整的实体代码块是:
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

public int ADPFileNumber { get; set; }

[Required]
public string ADUserName { get; set; }

public int AirCardCheckInLateCount { get; set; }

[Required]
public string Email { get; set; }

public DateTime? EndDate { get; set; }

[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

public int ManagerID { get; set; }
public string MobilePhone { get; set; }

[Required]
public string Office { get; set; }

[Required]
public string Phone { get; set; }

public decimal PTO { get; set; }
public DateTime StartDate { get; set; }
public int VehicleCheckInLateCount { get; set; }
public int WexCardDriverID { get; set; }

[ForeignKey("ManagerID")]
public User Manager { get; set; }

//Auditing Fields
public DateTime DateCreated { get; set; }
public int? UpdatedByUserID { get; set; }
public DateTime? DateUpdated { get; set; }
public DateTime LastAutoUpdate { get; set; }

[ForeignKey("UpdatedByUserID")]
public User UpdatedByUser { get; set; }
}

我错过了什么导致第二个自我引用中断?

最佳答案

您必须明确指出两个关联的主体端。您可以使用您最初拥有的类来做到这一点,而无需反向集合属性:

modelBuilder.Entity<User>()
.HasOptional(u => u.Manager)
.WithMany()
.HasForeignKey(u => u.ManagerID);
modelBuilder.Entity<User>()
.HasOptional(u => u.UpdatedByUser)
.WithMany()
.HasForeignKey(u => u.UpdatedByUserID);

请注意 ManagerID应该是 int?也是。您不能创建任何 User如果它需要另一个用户预先存在。这是一个先有鸡还是先有蛋的问题。

关于asp.net - 无法将第二个自引用 FK 添加到模型,导致无法确定主体结束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35656105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com