2013-02-18 111 views
0

什麼我迄今所做達到我想要使用實體框架是這樣的: 實體框架多階路徑錯誤

// 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. 

我是新來的實體框架,任何幫助將不勝感激。

回答

0

嘗試用單個多對多配置替換您的配置。

modelBuilder.Entity<User>() 
      .HasMany(a => a.Events) 
      .WithMany(b=> b.Guests) 
      .Map(x => 
      { 
       x.MapLeftKey("UserId"); 
       x.MapRightKey("EventId"); 
       x.ToTable("EventGuests"); 
      }); 
+0

在其他一些職位被建議試試這個:modelBuilder.Conventions.Remove ();我做了,現在它工作正常。謝謝。 – gplusplus 2013-02-18 12:39:01