【发布时间】:2013-04-05 02:48:55
【问题描述】:
我有 2 个实体,
- 新闻
- 文件附件
我想使用 code-first fluent API 进行配置,以便每个新闻可以有 0,1 或多个附件。
这是我现在正在使用的
public NewsMap()
{
this.ToTable("News"); // Table Name
this.HasKey(m => m.Id); // Primary Key
// Field Definition
this.Property(m => m.Title).HasMaxLength(255).IsRequired();
this.Property(m => m.Body).HasColumnType("Text").IsRequired();
this.Property(m => m.Summary).HasMaxLength(1000).IsRequired();
this.Property(m => m.AuthorId).IsRequired();
this.Property(m => m.CreatedOn).IsRequired();
this.Property(m => m.UpdatedOn).IsRequired();
this.HasMany(m => m.Attachments).WithMany().Map(m => m.MapLeftKey("NewsId").MapRightKey("AttachmentId"));
}
public class FileAttachmentMap : EntityTypeConfiguration<FileAttachment>
{
public FileAttachmentMap()
{
this.ToTable("FileAttachments"); // Table Name
this.HasKey(m => m.Id); // Primary Key
// Field Definition
this.Property(m => m.DisplayName).HasMaxLength(256).IsRequired();
this.Property(m => m.PhysicalFileName).HasMaxLength(256).IsRequired();
this.Property(m => m.Extension).HasMaxLength(50).IsRequired();
this.Property(m => m.IsImage).IsRequired();
this.Property(m => m.ThumbTiny).HasMaxLength(275).IsOptional();
this.Property(m => m.ThumbSmall).HasMaxLength(275).IsOptional();
this.Property(m => m.ThumbMid).HasMaxLength(275).IsOptional();
this.Property(m => m.ByteSize).IsRequired();
this.Property(m => m.StorageType).IsRequired();
this.Property(m => m.CreatedOn).IsRequired();
this.Property(m => m.UpdatedOn).IsRequired();
}
}
此映射正确生成了一个名为 NewsFileAttachment 的中间表,其中包含两个字段:
- NewsId
- 附件 ID
当我调用 News.Attachments.Add(Attachment); 时在新闻实体上它会在 Attachment 和 NewsAttachment 表中正确添加记录。
当我从 News.Attachments 中删除某些列表项时,它会正确地从 NewsAttachment 表中删除记录,但不会删除 FileAttachment 表中的记录。我也想删除它。
有人可以建议一个更好的 Fluent API 配置来实现这一点吗?
谢谢, 阿米特
编辑
就我而言,FileAttachment 存储用于各种目的的文件。我的博客实体也有附件。因此,有两个中间表 BlogAttachments 和 FileAttachments。现在,如果我使用 WithOptional 作为(我不能使用 WithRequired,因为我在 FileAttachment 表中都需要 BlogId 和 NewsId),我可以摆脱中间表,但仍然删除不会从 FileAttachment 表中删除记录,它只是让 NewsId/博客 ID 为空。
有什么建议吗?主要的是我不想用我在 FileAttachment 表中的所有字段创建单独的表。
【问题讨论】:
标签: entity-framework ef-code-first code-first fluent-interface entity-framework-migrations