EF Code First多对多无法正常工作

时间:2011-06-13 23:39:31

标签: c# entity-framework ef-code-first

使用实体框架代码第一范例我已将以下对象和关系定义为ASP.Net MVC3应用程序的一部分。问题是Photo和Gallery对象之间的多对多关系无法正常工作。

目前,图库可以包含许多照片 - 这是正确的。但是照片只能与一个图库相关联 - 这是不正确的。我希望照片能够出现在许多画廊中。如果我将照片添加到图库时已经与另一个图库相关联,则会将其从其他图库中删除。

我非常感谢您就如何使这种多对多关系发挥作用的解决方案。

这是我的代码:

public class Photo
{
    public int ID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Gallery> Galleries { get; set; }
}

public class Gallery
{
    public int ID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Photo> Photos { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    /* I would expect the following to cause a lookup table to 
     *  be created but it isnt */
    modelBuilder.Entity<Photo>().HasMany<Gallery>(p => p.Galleries);
    modelBuilder.Entity<Gallery>().HasMany<Photo>(g => g.Photos);
}

我在自己的自定义数据库初始化程序中使用以下代码。

public void InitializeDatabase(PhotoDBContext context)
{
    var dbCreationScript = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
    Log(dbCreationScript);
    context.Database.ExecuteSqlCommand(dbCreationScript);
}

通过记录dbCreationScript变量,我可以看到为这些表生成的相关sql如下所示。

create table [dbo].[Galleries] (
    [ID] [int] not null identity,
    [Title] [nvarchar](max) null,
    [Photo_ID] [int] null,
    primary key ([ID])
);

create table [dbo].[Photos] (
    [ID] [int] not null identity,
    [Title] [nvarchar](max) null,
    [Gallery_ID] [int] null,
    primary key ([ID])
);

alter table [dbo].[Photos] add constraint [Gallery_Photos] foreign key ([Gallery_ID]) references [dbo].[Galleries]([ID]);
alter table [dbo].[Galleries] add constraint [Photo_Galleries] foreign key ([Photo_ID]) references [dbo].[Photos]([ID]);

正如您所看到的,没有生成SQL来创建查找表,这可能是关系不起作用的原因 - 为什么不创建查找表?

1 个答案:

答案 0 :(得分:3)

我相信你需要使用这样的东西:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<Photo>()
            .HasMany<Gallery>(x => x.Galleries)
            .WithMany(x => x.Photos)
            .Map(x =>
            {
                x.MapLeftKey("ID");
                x.MapRightKey("ID");
                x.ToTable("GalleryPhotos");
            });
}
相关问题