Home > OS >  ModelBuilder seed data with relation keeped
ModelBuilder seed data with relation keeped

Time:02-16

it's probably very simple but i stuck and dont have idea how to solve it. I have two entities:

    public class BaseEntity
    {
        public int Id { get; set; }
        public DateTime CreatedDate { get; set; } = DateTime.Now;
        public DateTime ModifiedDate { get; set; } = DateTime.Now;
        public bool IsActive { get; set; } = true;
    }
    public class Vat : BaseEntity
    {
        public string Name { get; set; }
        public decimal Rate { get; set; }
        public Country Country { get; set; }
    }
    public class Country : BaseEntity
    {
        public string Name { get; set; }
        public string Code { get; set; }
        public ICollection<Vat> Vats { get; set; }
    }

and definition:

        public override void Configure(EntityTypeBuilder<Vat> builder)
        {
            base.Configure(builder);
            builder.HasOne(e => e.Country).WithMany(e => e.Vats);
        }

Seed look like that:

        modelBuilder.Entity<Country>().HasData(
            new Country { Id = 1, Code = "FR", Name = "France" },
            new Country { Id = 2, Code = "DE", Name = "Germany" },
            new Country { Id = 3, Code = "CZ", Name = "Czech" }
           );
        modelBuilder.Entity<Vat>().HasData(
           new Vat { Id = 1, Name = "23%", Rate = 23, IsActive = true, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, Country = new Country { Id = 1 },  },
           new Vat { Id = 2, Name = "8%", Rate = 8, IsActive = true, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, Country = new Country { Id = 1 } },
           new Vat { Id = 3, Name = "5%", Rate = 5, IsActive = true, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, Country = new Country { Id = 1 } },
           new Vat { Id = 4, Name = "0%", Rate = 0, IsActive = true, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, Country = new Country { Id = 1 } }
            );

But while i seeding Vat im getting this error:

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

Any idea what's the proper way to seed Vat entities and keep it related to Country?

CodePudding user response:

To seed entities with navigation properties you may use dynamic objects. This way should work:

modelBuilder.Entity<Vat>().HasData(
   new List<object>
        {
           new { Id = 1, Name = "23%", Rate = 23, IsActive = true, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, CountryId = 1  },
           new { Id = 2, Name = "8%", Rate = 8, IsActive = true, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, CountryId = 1  },
...
        }
   );
  • Related