实体框架核心播种联合表

发布于 2025-01-28 09:32:06 字数 2800 浏览 4 评论 0 原文

我正在与EF Core 7一起处理.NET Core 6。我需要在加入表中播种数据,但无法进行错误并获得错误。

我是种子 filetypeID ,但不确定为什么EF核心迁移抛出错误...

错误

The seed entity for entity type 'JobFileType' cannot be added because it has the navigation 'FileType' set. To seed relationships,  add the entity seed to 'JobFileType' and specify the foreign key values {'FileTypeId'}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.

classa

public class JobProfile
{
    public JobProfile()
    {
        this.JobFileTypes = new HashSet<JobFileType>();
    }

    public Guid JobProfileId { get; set; }
    public string Name { get; set; }
    public ICollection<JobFileType>? JobFileTypes { get; set; }
}

classb

public class FileType
{
    public FileType()
    {
        this.JobFileTypes = new HashSet<JobFileType>();
    }

    public Guid FileTypeId { get; set; }
    public string Extension { get; set; } = string.Empty;
    public ICollection<JobFileType>? JobFileTypes { get; set; }
}

joing表

 public class JobFileType
{
    public Guid JobFileTypeId { get; set; }
    public Guid JobProfileId { get; set; }
    public JobProfile JobProfile { get; set; } = new JobProfile();
    public Guid FileTypeId { get; set; }
    public FileType FileType { get; set; } = new FileType();
}

<代码>种子扩展

public static class JobFileTypeSeed
{
    public static void Seed(this ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<JobFileType>()
            .HasData(
                new JobFileType {JobFileTypeId = Guid.Parse("aaa"), JobProfileId = Guid.Parse("ccc"), FileTypeId = Guid.Parse("yyy") },
                new JobFileType { JobFileTypeId = Guid.Parse("bbb"), JobProfileId = Guid.Parse("ccc"), FileTypeId = Guid.Parse("zzz") }
              );
    }
}

config

internal class JobFileTypeConfiguration : IEntityTypeConfiguration<JobFileType>
{
    public void Configure(EntityTypeBuilder<JobFileType> builder)
    {
        builder.ToTable("JobFileType", "dbo");

        builder.HasKey(column => column.JobFileTypeId);

        builder
            .HasOne(jobFileType => jobFileType.JobProfile)
            .WithMany(jobProfile => jobProfile.JobFileTypes)
            .HasForeignKey(jobFileType => jobFileType.JobProfileId);

        builder
            .HasOne(jobFileType => jobFileType.FileType)
            .WithMany(fileType => fileType.JobFileTypes)
            .HasForeignKey(jobFileType => jobFileType.FileTypeId);
       
    }
}

I am working on .NET CORE 6 along with EF CORE 7. I need to seed data in joining table but unable to do so and get error.

I am seed FileTypeId but not sure why EF core migration throwing error...

error

The seed entity for entity type 'JobFileType' cannot be added because it has the navigation 'FileType' set. To seed relationships,  add the entity seed to 'JobFileType' and specify the foreign key values {'FileTypeId'}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.

ClassA

public class JobProfile
{
    public JobProfile()
    {
        this.JobFileTypes = new HashSet<JobFileType>();
    }

    public Guid JobProfileId { get; set; }
    public string Name { get; set; }
    public ICollection<JobFileType>? JobFileTypes { get; set; }
}

ClassB

public class FileType
{
    public FileType()
    {
        this.JobFileTypes = new HashSet<JobFileType>();
    }

    public Guid FileTypeId { get; set; }
    public string Extension { get; set; } = string.Empty;
    public ICollection<JobFileType>? JobFileTypes { get; set; }
}

Joing Table

 public class JobFileType
{
    public Guid JobFileTypeId { get; set; }
    public Guid JobProfileId { get; set; }
    public JobProfile JobProfile { get; set; } = new JobProfile();
    public Guid FileTypeId { get; set; }
    public FileType FileType { get; set; } = new FileType();
}

Seed Extension

public static class JobFileTypeSeed
{
    public static void Seed(this ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<JobFileType>()
            .HasData(
                new JobFileType {JobFileTypeId = Guid.Parse("aaa"), JobProfileId = Guid.Parse("ccc"), FileTypeId = Guid.Parse("yyy") },
                new JobFileType { JobFileTypeId = Guid.Parse("bbb"), JobProfileId = Guid.Parse("ccc"), FileTypeId = Guid.Parse("zzz") }
              );
    }
}

config

internal class JobFileTypeConfiguration : IEntityTypeConfiguration<JobFileType>
{
    public void Configure(EntityTypeBuilder<JobFileType> builder)
    {
        builder.ToTable("JobFileType", "dbo");

        builder.HasKey(column => column.JobFileTypeId);

        builder
            .HasOne(jobFileType => jobFileType.JobProfile)
            .WithMany(jobProfile => jobProfile.JobFileTypes)
            .HasForeignKey(jobFileType => jobFileType.JobProfileId);

        builder
            .HasOne(jobFileType => jobFileType.FileType)
            .WithMany(fileType => fileType.JobFileTypes)
            .HasForeignKey(jobFileType => jobFileType.FileTypeId);
       
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小兔几 2025-02-04 09:32:06

关于具体问题(BTW并非特定于加入实体,而是任何实体模型种子),没有太多要说的:

我是种子 filetypeid ,但不确定为什么EF核心迁移抛出错误...

由于问题的开头包括在错误消息的开头:

因为它具有导航“ Filetype”集。

并且您的实体具有

public FileType FileType { get; set; } = new FileType();
//                                     ^  ^   ^
//                                     the problem

相同的内容,

public JobProfile JobProfile { get; set; } = new JobProfile();

如果您解决原始内容,则将是下一个错误。

删除两个导航属性初始化器( = new ... ),问题将消失。

一般而言,您应该从不 初始化参考导航属性,因为它会导致许多副作用和/或不当行为(不仅用于播种,而且还渴望/懒惰/explicit数据加载)。初始化集合导航属性是任意的,但是还可以。只能避免参考导航属性初始化。有关更多信息,请参见 ef codefirst:我应该初始化导航属性吗?? - 旧的EF主题,但仍然适用。

如果您想解决NRT警告(我想),则使用 new 初始化绝对不是正确的方法。我不喜欢NRT的原因之一是因为它迫使人们使用“解决方法”来防止编译器警告,这实际上破坏了主要功能。特别是在EF Core中,启用NRT还更改了某些属性的可选/所需属性,因此数据库列类型(最明显的是 String properties/larter/colums和Reference Navigations)。您可以在官方EF核心文档中的主题,但总的来说,我只是为EF实体模型类禁用NRT。

There is not much to say about the concrete issue (which btw is not specific to joining entity, but any entity model seeding):

I am seed FileTypeId but not sure why EF core migration throwing error...

as the cause of the issue is included at the beginning of the error message:

because it has the navigation 'FileType' set.

And your entity has

public FileType FileType { get; set; } = new FileType();
//                                     ^  ^   ^
//                                     the problem

and the same for

public JobProfile JobProfile { get; set; } = new JobProfile();

which will be the next error if you resolve the original.

Remove both navigation property initializers (= new ...) and the problem will be gone.

As a general rule, you should never initialize reference navigation properties because it causes many side effects and/or improper behaviors (not only for seeding, but also eager/lazy/explicit data loading). Initializing collection navigation properties is arbitrary, but ok. Only reference navigation property initialization must be avoided. For more info, see EF codefirst : Should I initialize navigation properties? - quite old EF topic, but still applies.

If you are trying to resolve NRT warnings (as I guess), initializing with new is definitely not a proper way. One reason I don't like NRT is because it is forcing people to use "workarounds" for preventing compiler warnings, which in fact break the primary functionality. Specifically in EF Core, enabling NRT also changes the optional/required attribute of some properties, hence database column types (most noticeable for string properties/columns and reference navigations). You could read more about this in the Working with Nullable Reference Types topic in the official EF Core documentation, but in general I would just disable NRT for EF entity model classes.

川水往事 2025-02-04 09:32:06

适当的订单是首先设置“主数据”,然后尝试设置加入表。

违约

{get;set;} = new Something();

可能是有问题的声明,因为创建时的任何实例都将具有已设置的关系filetype

The proper order is to set the "master data" first and then try to set the join table, as you would expect.

The defaulting

{get;set;} = new Something();

Could be the offending declaration, since any instance upon creation will have the relation JobFileType already set

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文