我正在使用EF4 Code-First進行建模,從事ASP.NET MVC中的項目工作。我有以下的模型類:在EF4代碼中創建多對多關係代碼優先
public class ComicBook
{
public long ComicBookID { get; set; }
public string IssueTitle { get; set; }
public int IssueNumber { get; set; }
public DateTime PublishDate { get; set; }
public IList<ComicBookPerson> Writers { get; set; }
public IList<ComicBookPerson> Pencillers { get; set; }
public IList<User> CollectingUsers { get; set; }
}
public class ComicBookPerson
{
public long ComicBookPersonID { get; set; }
public string Name { get; set; }
public IList<ComicBook> WorkedOnComicBooks { get; set; }
}
public class User
{
[Key]
public long UserID { get; set; }
public string Email { get; set; }
public IList<ComicBook> CollectedBooks { get; set; }
}
而下面的DbContext:
public class ComicContext : DbContext
{
public DbSet<ComicBook> ComicBooks { get; set; }
public DbSet<ComicBookPerson> ComicBookPerson { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ComicBook>()
.HasMany(b => b.Writers)
.WithMany(w => w.WorkedOnComicBooks)
.Map(t => t.MapLeftKey("ComicBookID")
.MapRightKey("WriterID")
.ToTable("ComicBook_Writers"));
modelBuilder.Entity<ComicBook>()
.HasMany(b => b.Pencillers)
.WithMany(p => p.WorkedOnComicBooks)
.Map(t => t.MapLeftKey("ComicBookID")
.MapRightKey("PencillerID")
.ToTable("ComicBook_Penciller"));
}
}
的規則,需要應用有:
- 用戶可以有很多ComicBooks他們收集
- 漫畫書可以在衆多用戶的收藏中
- 每個漫畫書都可以有1個或多個作家
- 每個ComicBook可以有1個或多個Pencillers
- 一個ComicBookPerson可以在任何一本書
- 一個ComicBookPerson可以在很多書工作作家或Penciller,作爲一個作家,Penciller,或兩者
用戶和ComicBooks之間的多對多模式創建得很好。這是多人對ComicBooks和ComicBookPersons之間正在打破。我得到的錯誤消息是:
Schema specified is not valid. Errors:
(15,6) : error 0040: Type ComicBook_Writers is not defined in namespace Comics.Models (Alias=Self).
我基本上想要兩個連接表,一個名爲ComicBook_Writers,一個名爲ComicBookPencillers。這兩個表將包含一個ComicBookID和一個ComicBookPersonID。 EF Code First有可能嗎?
工作正常。很簡單,謝謝! – 2011-12-19 04:36:01