我正在使用EF4 Code-First进行ASP.NET MVC项目的建模。我有以下模型类:
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和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中是否可行?
答案 0 :(得分:2)
您需要ComicBookPerson
类中与作家和铅笔有关的两个集合属性。
public class ComicBookPerson
{
public long ComicBookPersonID { get; set; }
public string Name { get; set; }
public IList<ComicBook> WroteComicBooks { get; set; }
public IList<ComicBook> PenciledComicBooks { get; set; }
}
模型映射为
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ComicBook>()
.HasMany(b => b.Writers)
.WithMany(w => w.WroteComicBooks)
.Map(t => t.MapLeftKey("ComicBookID")
.MapRightKey("WriterID")
.ToTable("ComicBook_Writers"));
modelBuilder.Entity<ComicBook>()
.HasMany(b => b.Pencillers)
.WithMany(p => p.PenciledComicBooks)
.Map(t => t.MapLeftKey("ComicBookID")
.MapRightKey("PencillerID")
.ToTable("ComicBook_Penciller"));
}
答案 1 :(得分:0)
我认为这种模式接近正确,但仍然缺少某些东西
ComicBookPerson
可以是作家和施法者,这意味着您仍然需要在班级ComicBookPerson
中使用第三个列表:
public IList<ComicBook> WroteComicBooks { get; set; }
public IList<ComicBook> PenciledComicBooks { get; set; }
public IList<ComicBook> WrotPencComicBooks { get; set; }
我是对的吗?