I am working on a project in ASP.NET MVC using EF4 Code-First for the modeling. I have the following model classes:
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; }
}
And the following 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"));
}
}
The rules that need to apply are:
- Users can have many ComicBooks in their collection
- ComicBooks can be in many users’ collections
- Each ComicBook can have 1 or more Writers
- Each ComicBook can have 1 or more Pencillers
- A ComicBookPerson can be a Writer or a Penciller on any book
- A ComicBookPerson can work on many books, as a Writer, Penciller, or both
The many-to-many schema between Users and ComicBooks is created fine. It is the many-to-many between ComicBooks and ComicBookPersons that is breaking. The error message I get is:
Schema specified is not valid. Errors:
(15,6) : error 0040: Type ComicBook_Writers is not defined in namespace Comics.Models (Alias=Self).
I basically want two join tables, one called ComicBook_Writers and one called ComicBookPencillers. Both tables will contain a ComicBookID and a ComicBookPersonID. Is this possible in EF Code First?
You need two collection properties in
ComicBookPersonclass that relates to writers and pencillers.Model mapped as