Reputation: 43
I'm setting up a migration in an MVC5 that has a Model that's called "Order" with 3 properties, one of them is a class of PizzaModel. PizzaModel has the code below, what I'm trying to do is to enable multiple instances of pizzas in a single Order, so one Order can have many pizzas.
public class PizzaModel
{
[Key]
public int Id { get; set; }
public List<PizzaSet> Pizzas { get; set; }
public int Cost { get; set; }
}
public class PizzaSet
{
public enum Toppings { GreenOlives, BulgarianCheese, Onions, Mushrooms, Peppers, Basil, Sausage, Pepperoni, Ham, Beef }
public enum Sauces { BBQ, Islands }
public enum Size { Personal, Medium, Family }
public Size PizzaSize { get; set; }
public List<Sauces> PizzaSauces { get; set; }
public List<Toppings> PizzaToppings { get; set; }
}
Is this a wrong approach for a migration?
Upvotes: 2
Views: 260
Reputation: 17658
You have enums
as your list type.
If youre storing this data in a database. The database needs a placeholder to store the enum values.
In general this is done by a table.
So, if you make classes of your enums, these will be translated to tables and the mapping will work.
public class Topping
{
public string Name {get;set;}
}
Use this class as your list type.
Do note that you need to fill the topping
, sauces
and etc. tables. The good news is: you can extend them without changing the code :-)
Alternatively, you can put the
[NotMapped]
attribute on your property. Do note that this won't help you in your specific case because it would not store the toppings in the database then.
Upvotes: 1
Reputation: 1689
Your PizzaSet
class is using a List of Enums, which will not map to a database schema in EF.
If you want to use an enum for Sauces
and Toppings
and want to allow multiple selections, you need to use the [Flags]
property for the enum, to treat it as a bit field.
public class PizzaSet
{
[Flags]
public enum Toppings { GreenOlives = 1, BulgarianCheese = 2, Onions = 4, Mushrooms = 8, Peppers = 16, Basil = 32, Sausage = 64, Pepperoni = 128, Ham = 256, Beef = 512 }
[Flags]
public enum Sauces { BBQ = 1, Islands = 2 }
public enum Size { Personal, Medium, Family }
public Size PizzaSize { get; set; }
public Sauces PizzaSauces { get; set; }
public Toppings PizzaToppings { get; set; }
}
Then Toppings
and Sauces
become a bit field of possible values (notice the values will need to represent unique bits)
To select multiple toppings:-
PizzaSet ps = new PizzaSet();
ps.Toppings = Toppings.GreenOlives | Toppings.Peppers;
However, given your list of toppings and sauces may change over time, it's probably better to have a separate table that lists toppings, and use a join table (since it's EF Core)
Upvotes: 2