Mətin Abaszadə
Mətin Abaszadə

Reputation: 13

Can we seed data with shadow properties in Ef Core

I'm working on an Entity Framework Core project and I'm unsure about using shadow properties as foreign keys and how to seed data in this scenario.

I have two classes, Brand and Model, with a one-to-many relationship where Brand can have multiple Models. I've defined the entities as follows:

public class Brand
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public List<Model> Models { get; set; } = new List<Model>();
}

public class Model
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
}

To establish the foreign key relationship using a shadow property, I've configured the model builder as follows:

modelBuilder.Entity<Model>()
              .HasOne<Brand>()
              .WithMany(b => b.Models)
              .HasForeignKey("BrandId")
              .IsRequired();

When adding live data manually, everything works fine. For example:

 static async Task Main(string[] args)
{
    Console.OutputEncoding = System.Text.Encoding.UTF8;
    AppDbContext dbContext = new AppDbContext();

    var brand = new Brand()
    {
        Name = "BMW",
        Models = new List<Model>()
        {
            new Model()
            {
                Name = "3 series"
            }
        }
    };

    dbContext.Brands.Add(brand);
    dbContext.SaveChanges();
}

However, when I try to seed data using the HasData method, I'm encountering issues. Here's an example of how I'm trying to seed data:

var brands = new Brand()
{
    Name = "Mercedes",
    Models = new List<Model>()
    {
        new Model()
        {
            Name = "E class"
        }
    }
};

modelBuilder.Entity<Brand>().HasData(brands);

In this case, the seeding does not work as expected. My question is, can we use shadow properties as foreign keys when seeding data in Entity Framework Core? If so, how can I achieve this?

Thank you for any help and guidance.

Upvotes: 1

Views: 407

Answers (1)

EmiFala
EmiFala

Reputation: 91

I had the same problem.

Seed Models data this way

modelBuilder.Entity<Model>().HasData(
new
{
    Id = 1,
    Name = "YourModelName",
    BrandId = 1
},
new
{
    Id = 2,
    Name = "OtherModelName",
    BrandId = 1
},
...);

Upvotes: 2

Related Questions