开发者

EF Code First Many-to-Many not working

Using the Entity Framework Code First paradigm I have defined the following objects and relationships as part of an ASP.Net MVC3 application. The problem is the many-to-many relationship between the Photo and Gallery o开发者_StackOverflow社区bjects is not working properly.

Currently a gallery can contain many photos - this is correct. But a photo can only be associated with one Gallery - this is incorrect. I want a photo to be able to be in many galleries. If I add a photo to a gallery when it is already associated with another gallery, it is removed from the other gallery.

I would very much appreciate your solutions on how to make this many-to-many relationship work.

Here's my code:

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);
}

I am using the following code within my own custom database initializer.

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

By logging the dbCreationScript variable I can see that the relevant sql that is generated for these tables is as follows.

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]);

As you can see there is no SQL generated to create a lookup table which is probably why the relationship is not working - why isnt a lookup table being created?


I believe you need to use something like this:

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");
            });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜