Home > Net >  How to seed data without specifying relations
How to seed data without specifying relations

Time:12-28

I have entity as below:

public class EntityA
{
    public int Id { get; init; }
    public bool Enabled { get; set; } = true;
    public string Name { get; set; }
    public string Description { get; set; }
    public int SomeEntityId { get; set; }
    public SomeEntity SomeEntity { get; set; }
}

and the SomeEntity:

public class SomeEntity
{
    public int Id { get; init; }
    public string Name { get; set; }
    public ICollection<EntityA> EntitiesA { get; set; }
}

I want to seed EntityA without any relations:

public void Configure(EntityTypeBuilder<EntityA> builder)
{
    builder.HasData(new EntityA
    {
        Id = 1,
        Enabled = true,
        Name = "...",
        Description = "..."
    });
}

But I always get error while update-database that:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_EntitiesA_SomeEntities_SomeEntityId". The conflict occurred in database "DatabaseName", table "dbo.SomeEntities", column 'Id'. The statement has been terminated.

I know that it occurs because EF want's my SomeEntity to be not null, but I can't do it nullable because this seeded data is really unique (it's only data that will haven't foreign key).

How can I get around this?

CodePudding user response:

To seed data without specifying relations in Entity Framework Core, you can set the foreign key property to null or to a default value that is defined in the database.

For example, in your case, you can set the SomeEntityId property to null when seeding the EntityA entity:

    public void Configure(EntityTypeBuilder<EntityA> builder)
{
    builder.HasData(new EntityA
    {
        Id = 1,
        Enabled = true,
        Name = "...",
        Description = "...",
        SomeEntityId = null
    });
}

Alternatively, you can set the SomeEntityId property to a default value that is defined in the database. For example, if you have a default value of 0 defined for the SomeEntityId column in the EntityA table, you can use the following code to seed the EntityA entity:

public void Configure(EntityTypeBuilder<EntityA> builder)
{
    builder.HasData(new EntityA
    {
        Id = 1,
        Enabled = true,
        Name = "...",
        Description = "...",
        SomeEntityId = 0
    });
}

hope this fixes what you need.

  • Related