.net-core - 如何从 Entity Framework Core 中的模型中删除导航属性?
问题描述
我正在尝试通过删除导航属性来更改 EF Core 中的模型,但是当我这样做时,项目不会为我构建以添加迁移。我明白为什么,但由于我不是 Fluent API 的专家,我不确定删除该属性的最佳方法。
我要删除的属性是 Images 属性(我想将其更改为一对一关系而不是一对多)。
public partial class DiaryEntries
{
public long Id { get; set; }
public DateTime Date { get; set; }
public string Content { get; set; }
public long DiaryId { get; set; }
public Diaries Diary { get; set; }
public ICollection<Images> Images { get; set; }
}
public partial class Images
{
public int Id { get; set; }
public string Filename { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public long DiaryEntryId { get; set; }
public DiaryEntries DiaryEntry { get; set; }
}
定义关系的代码是:
modelBuilder.Entity<Images>(entity =>
{
entity.ToTable("Images", "dbo");
entity.HasIndex(e => e.DiaryEntryId)
.HasName("IX_FK_DiaryEntryImages");
entity.Property(e => e.DiaryEntryId).HasColumnName("DiaryEntry_Id");
entity.Property(e => e.Filename).IsRequired();
entity.Property(e => e.Title).HasMaxLength(128);
entity.HasOne(d => d.DiaryEntry)
.WithMany(p => p.Images)
.HasForeignKey(d => d.DiaryEntryId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_DiaryEntryImages");
});
显然,如果我ICollection<Images> Images
从模型中删除导航属性,那么它将不再存在并且会导致上面的代码出错。那么,删除导航属性的最佳方法是什么?
解决方案
我不清楚你为什么想要一对一的关系?一本日记可以有多个图像,对吗?不过,要回答这个问题,只需从您的 fluent api 以及导航属性中删除最后一个块。如果您想更改为一对一 - 您的流利 api 应该如下所示。
modelBuilder.Entity<Images>()
.HasOne(a => a.Diary)
.WithOne(b => b.Images)
.HasForeignKey<Diary>(b => b.DiaryId);
另外一点,您的类名应该是单数而不是复数:-)
推荐阅读
- ms-project - 在 Excel 工作簿上使用 MS 项目 vba,我想将工作表移动到最左边的选项卡
- c# - TypeLoadException 因为控制器中的文件?
- vue.js - Buefy 导航栏组件中可能存在的错误
- google-app-maker - 在应用程序制造商中,如何清除列排序?
- vue.js - node-sass 和 sass-loader - 模块构建失败:TypeError: this.getResolve is not a function at Object.loader
- r - “文件错误(文件,“r”):无法打开连接”
- javascript - 从实时数据库中检索 currentUser 数据
- spring - 将 spring boot 从 2.1.9 升级到 2.2.0 ,现在启动时出现异常
- svg - 如何根据每个弧度百分比在svg圆中绘制几条弧?
- javascript - 使用 Angular firestore 在 firebase 中返回子集合