首页 > 解决方案 > 如何从 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从模型中删除导航属性,那么它将不再存在并且会导致上面的代码出错。那么,删除导航属性的最佳方法是什么?

标签: .net-coreentity-framework-core

解决方案


我不清楚你为什么想要一对一的关系?一本日记可以有多个图像,对吗?不过,要回答这个问题,只需从您的 fluent api 以及导航属性中删除最后一个块。如果您想更改为一对一 - 您的流利 api 应该如下所示。

modelBuilder.Entity<Images>()
        .HasOne(a => a.Diary)
        .WithOne(b => b.Images)
        .HasForeignKey<Diary>(b => b.DiaryId);

另外一点,您的类名应该是单数而不是复数:-)


推荐阅读