具有InverseProeprty的同一集合Entity Framework 6上的多对多和一对多

时间:2019-01-21 13:15:42

标签: c# .net entity-framework entity-framework-6

我有以下内容:

public class Event : IEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonProperty("id")]
    public Guid Id { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("date")]
    public DateTimeOffset Date { get; set; }

    [JsonProperty("distance")]
    public int Distance { get; set; }

    [JsonProperty("verticalAscend")]
    public int VerticalAscend { get; set; }

    [ForeignKey("User")]
    [JsonProperty("userId")]
    public Guid UserId { get; set; }

    //attending
    public DateTimeOffset DateCreated { get; set; }
    public DateTimeOffset DateModified { get; set; }

    [JsonProperty("user")]
    public virtual User User { get; set; }
    [JsonProperty("comments")]
    public virtual ICollection<Comment> Comments { get; set; }
    [JsonProperty("attending")]
    public virtual ICollection<User> AttendingList { get; set; }
}

并且:

public class User : IEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonProperty("id")]
    public Guid Id { get; set; }

    [JsonProperty("profilePicUrl")]
    public string ProfilePicUrl { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("surname")]
    public string LastName { get; set; }

    [JsonProperty("email")]
    public string Email { get; set; }

    public DateTimeOffset DateCreated { get; set; }
    public DateTimeOffset DateModified { get; set; }

    public virtual ICollection<Event> AttendingEvents { get; set; }
    [InverseProperty("User")]
    public virtual ICollection<Event> Events { get; set; }
}

关系:

事件:

  • 许多用户参加(AttendingList)

用户:

  • 可以参加很多活动(AttendingEvents)

  • 可以创建多个事件(事件)

Event.AttendingList与User.AttendingEvents之间存在许多关系。 Event.User和User.Events之间存在0-很多关系,其中ForeignKey作为UserId。

我正在尝试使用Fluent API来配置它们,并使用InverseProperty来配置关系的另一端,映射回Event.User,但是会出现以下错误:

  

在表'UserEvents'上引入FOREIGN KEY约束'FK_dbo.UserEvents_dbo.Events_Event_Id'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

我不确定如何在一张桌子上解决这种关系。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

DbContext中,按以下方式配置模型:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<Event>().HasRequired(e => e.User)
            .WithMany(u => u.Events)
            .HasForeignKey(e => e.UserId)
            .WillCascadeOnDelete(false);

     modelBuilder.Entity<User>()
            .HasMany<Event>(s => s.AttendingEvents)
            .WithMany(c => c.AttendingList)
            .Map(cs =>
            {
                cs.MapLeftKey("UserId");
                cs.MapRightKey("EventId");
                cs.ToTable("UserEvents");
            });
}