2

I've got two classes

public class Category { public int Id { get; set; } public string Name { get; set; } } public class Item { public int Id { get; set; } public sting Name { get; set; } public Category Category { get; set; } } 

I have EF Migrations and the following seed:

var instockCategory = new Category() { Name = "InStock" }; var outofStockCategory = new Category() { Name = "OutOfStock" }; context.Items.AddOrUpdate( d => d.Name, new Item() { Name = "Item1", Category = instockCategory }, new Item() { Name = "Item2", Category = outofStockCategory }, new Item() { Name = "Item3", Category = outofStockCategory } ); 

The line "d => d.Name" makes sure that based on the name of the item, there won't be duplicate records when I reseed the database. However, the first time I execute this, two categories are created with id 1 and 2. But the second time I run this, 3 new categories are created! Can I fix this without manually adding every single category first?

1 Answer 1

3

You have to use AddOrUpdate for your categories too.

var instockCategory = default(Category); var outofStockCategory = default(Category); context.Set<Category>().AddOrUpdate( c => c.Name, instockCategory = new Category() { Name = "InStock" }, outofStockCategory = new Category() { Name = "OutOfStock" } ); context.Items.AddOrUpdate( d => d.Name, new Item() { Name = "Item1", Category = instockCategory }, new Item() { Name = "Item2", Category = outofStockCategory }, new Item() { Name = "Item3", Category = outofStockCategory } ); 

An explicit DbSet on your Context class is not necessary.

public class Context : DbContext { public DbSet<Item> Items { get; set; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Probably, but I don't want to, because then I'd have to add a Categories DbSet and for now I don't have it. Can still do it, just asking if something else was possible.
@DennisvanderStelt does the updated answer help? What exactly do you mean with "add a Categories DbSet"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.