Entity Framework Core cannot create Seed with Child objects and GUID's

.net-core entity-framework-core

Question

Let's say I have the following entities:

 public class Artist
 {
     [Key]
     public Guid Id { get; set; }

     [Required]
     public string Name { get; set; }
 }

public class Song
{
    [Key] 
    public Guid Id { get; set; }

    [Required] 
    public string Name { get; set; }

    [Required]  
    public Artist Artist { get; set; }
}

For the Song class I'm trying to create a seed like for example:

modelBuilder.Entity<Song>().HasData(new Song
    {
        Id = Guid.NewGuid(),
        Name = "test",
        Artist = new Artist
        {
            Id = Guid.NewGuid(),
            Name = "test"
        }
    });

This is throwing the following error:

The seed entity for entity type 'Song' cannot be added because there was no value provided for the required property 'ArtistId'.

I have no clue why I keep getting this error. When I try to seed the Artist object only, I have no issues. I also tried referencing an existing Artist object, however the result where the same.

Edit: I forgot to mention that the code can indeed run, however when trying to create a migration through the Add-Migration InitialCreate command, the error shows.

1
4
8/6/2018 6:42:22 AM

Accepted Answer

I found a solution using an anonymous object (new {}). The problem was that my Song object didn't contain a Guid ArtistId property, but an Artist Artist property. However for some reason, EF migrations cannot relate with this object and required an id instead. With an anonymous object this could be fixed like so:

modelBuilder.Entity<Song>().HasData(new //No Song object here.
{
    Id = Guid.NewGuid(),
    Name = "test",
    ArtistId = artist.Id
});

and now I can run my migration.

Update: I think the easier way to insert seed data now is to generate an empty migration and add your data through the migrationBuilder.Sql() method.

5
12/20/2018 8:15:41 AM

Popular Answer

agree with @vivek nuna First seed Artist and then seed Song, Please use ArtistId while seeding.

var artist = new Artist()
{
    Id = Guid.NewGuid(),
    Name = "test-a"
};

modelBuilder.Entity<Artist>().HasData(artist);
modelBuilder.Entity<Song>().HasData(new Song()
{
    Id = Guid.NewGuid(),
    Name = "test",
    ArtistId = artist.Id
});

I could add migrations using "Add-Migration" command.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow