0

到目前为止,为了使用 Entity Framework 实现我想要的,我所做的事情是这样的:

// User.cs
public class User {
  public Guid ID { get; set; } // column: user_id
  public virtual ICollection<Event> Events { get; set; }
}
// Event.cs
public class Event {
  public Guid ID { get; set; } // column: event_id
  public virtual Guid UserID { get; set; } // column: event_userid
  public virtual ICollection<User> Guests { get; set; }
}
// MyAppContext.cs
...
protected override void OnModelCreating(DbModelBuilder mb) {
  mb.Entity<User>()
    .HasKey(u => u.ID)
    .HasMany(u => u.Events)
    .WithOptional()
    .HasForeignKey(e => e.UserID);

  mb.Entity<Event>()
    .HasKey(e => e.ID)
    .HasMany(e => e.Guests)
    .WithMany();
}
...

我期望数据库结构如下:

TABLE: user
user_id uniqueidentifier not null primary key

TABLE: event
event_id uniqueidentifier not null primary key
event_userid uniqueidentifier not null foreign key references user(user_id)

TABLE: event_guests
event_id uniqueidentifier not null
user_id uniqueidentifier not null

我有一种感觉,我上面使用的流畅 API 不会提供预期的数据库结构,而且,我得到以下异常,我不知道如何修复:

Introducing FOREIGN KEY constraint 'FK_xxx' on table 'event_guests'
may cause cycles or multiple cascade paths. Specify ON DELETE NO
ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.

我是实体框架的新手,任何帮助将不胜感激。

4

1 回答 1

0

Try replacing your configurations with a single many to many configuration.

modelBuilder.Entity<User>()
            .HasMany(a => a.Events)
            .WithMany(b=> b.Guests)
            .Map(x =>
            {
                x.MapLeftKey("UserId");
                x.MapRightKey("EventId");
                x.ToTable("EventGuests");
            });
于 2013-02-18T02:27:15.330 回答