我已经在这里工作了几个小时,并尝试了许多我找到的建议,但没有运气。我正在使用代码EF 5。
情况是我有一个班级员工。然后我有另一个有两个属性的类,它们都是Employee类型。我希望这两者都是外键约束,但是要求允许来自同一用户的许多相同请求,因此我不能仅将它们用作键。我并不真正关心Employee有两个导航系列,但在我处理这个似乎是一个要求的问题时。如果它简化了问题我可以删除它们。
我收到此消息。 System.Data.Entity.Edm.EdmAssociationEnd :: Multiplicity在关系'Employee_RequestsForEmployee'中的角色'Employee_RequestsForEmployee_Target'中无效。由于Dependent Role属性不是关键属性,因此Dependent Role的多重性的上限必须为'*'。
我在上下文的OnModelCreation方法中使用Fluent API尝试了这个;
modelBuilder.Entity() .HasRequired(u => u.ForEmployee) 。和很多() .HasForeignKey(u => u.ForEmployeeId);
modelBuilder.Entity<RevenueTransferRequest>() .HasRequired(u => u.FromEmployee) .WithMany() .HasForeignKey(u => u.FromEmployeeId);
冲突中的类是(我为了清楚起见删除了一些属性);
public class Employee : IEmployee
{
[Key]
public string Id { get; set; }
[InverseProperty("ForEmployee")]
public ICollection<RevenueTransferRequest> RequestsForEmployee { get; set; }
[InverseProperty("FromEmployee")]
public ICollection<RevenueTransferRequest> RequestsFromEmployee { get; set; }
}
public class RevenueTransferRequest : IRevenueTransferRequest
{
[Key]
public Guid Id { get; set; }
[Required]
[ForeignKey("ForEmployee")]
public String ForEmployeeId { get; set; }
[InverseProperty("RequestsForEmployee")]
public Employee ForEmployee { get; set; }
[Required]
[ForeignKey("FromEmployee")]
public String FromEmployeeId { get; set; }
[InverseProperty("RequestsFromEmployee")]
public Employee FromEmployee { get; set; }
}
非常感谢任何帮助。提前谢谢。
答案 0 :(得分:3)
我从来没有弄清楚如何使用数据注释,但使用Fluent API,我能够做到这一点。我缺少的是我必须在HasMany()方法中指定另一方的关系是我通过数据注释和约定理解的。
这在DbContext OnModelCreating覆盖中调用(WillCascadeOnDelete(false)与另一个问题相关)。
modelBuilder.Entity<RevenueTransferRequest>()
.HasRequired(e => e.FromEmployee)
.WithMany(x=>x.RequestsFromEmployee)
.WillCascadeOnDelete(false);
modelBuilder.Entity<RevenueTransferRequest>()
.HasRequired(e => e.ForEmployee)
.WithMany(x => x.RequestsForEmployee)
.WillCascadeOnDelete(false);
使用课程:
[Key]
public String Id { get; set; }
public String BusinessUnitLeaderId { get; set; }
public Employee BusinessUnitLeader { get; set; }
[Required]
[MaxLength(150)]
public String DisplayName { get; set; }
public ICollection<Project> BusinessUnitLeaderProjects { get; set; }
public ICollection<RevenueTransferRequest> RequestsForEmployee { get; set; }
public ICollection<RevenueTransferRequest> RequestsFromEmployee { get; set; }
public class RevenueTransferRequest
{
[Key]
public Guid Id { get; set; }
[Required]
public String ForEmployeeId { get; set; }
public Employee ForEmployee { get; set; }
[Required]
public String FromEmployeeId { get; set; }
public Employee FromEmployee { get; set; }
[Required]
public String ProjectId { get; set; }
public Project Project { get; set; }
[Required]
public Double? TransferAmount { get; set; }
public int WorkflowState { get; set; }
}