EF代码首先多对多不起作用
|
使用实体框架代码优先范式,我已经定义了以下对象和关系作为ASP.Net MVC3应用程序的一部分。问题是照片和图库对象之间的多对多关系无法正常工作。
目前,图库可以包含许多照片-这是正确的。但是一张照片只能与一个图库相关联-这是不正确的。我希望照片能够出现在许多画廊中。如果我已将照片添加到画廊中,而该照片已经与另一个画廊相关联,则会将其从另一个画廊中删除。
非常感谢您提供有关如何使这种多对多关系有效的解决方案。
这是我的代码:
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 个回复
贡炮逗握惫