'Ef Core Data Seeding

Hi folks I have problem with data seeding. When I try to seed this entity:

modelBuilder.Entity<Place>().HasData(new Place
        {
            Id = Guid.NewGuid().ToString(),
            Name = "Europe",
            PlaceIsContainedIn = new Place
            {
                Id = Guid.NewGuid().ToString(),
                IdPlaceIsContainedIn = Guid.NewGuid().ToString(),
                Name = "Bulgaria",
                LevelNo = 0,
            }
        });

This error appears me:

The seed entity for entity type 'Place' cannot be added because it has the navigation 'PlaceIsContainedIn' set. To seed relationships, add the entity seed to 'Place' and specify the foreign key values {'IdPlaceIsContainedIn'}.

I have this Place class:

public class Place
{
    public string Id { get; set; } = Guid.NewGuid().ToString();

    [ForeignKey(nameof(PlaceIsContainedIn))]
    public string? IdPlaceIsContainedIn { get; set; }

    public Place PlaceIsContainedIn { get; set; }

    public string Name { get; set; }

    public int LevelNo { get; set; }

    public ICollection<Contact> ContinentContacts { get; set; } = new HashSet<Contact>();

    public ICollection<Contact> CountryContacts { get; set; } = new HashSet<Contact>();

    public ICollection<Contact> CityContacts { get; set; } = new HashSet<Contact>();
}

This is my context:

modelBuilder.Entity<Place>().Property(x => x.Name).HasColumnType("nvarchar(50)");
        modelBuilder.Entity<Place>().Property(x => x.LevelNo).HasColumnType("tinyint");
        modelBuilder.Entity<Place>().HasOne(x => x.PlaceIsContainedIn).WithMany().OnDelete(DeleteBehavior.Restrict);
        modelBuilder.Entity<Place>().Property(x => x.IdPlaceIsContainedIn).IsRequired(false);

Please, if anyone knows how to solve the problem, I will be happy if you share with me.



Solution 1:[1]

You can map them only by foreign keys

     modelBuilder.Entity<Place>().HasData(
                   new 
                {
                    Id = "dsfsdg",
                    Name = "Bulgaria",
                    LevelNo = 0,
                    
                }, 
                   new
                {
                    Id = "423412fsd",
                    Name = "Europe",
                    IdPlaceIsContainedIn  ="dsfsdg" //pk of the above entity
                } 
                   );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael