2013-02-18 194 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