How can I initialize Features as a literal list?
UPDATE
As quite rightly pointed out by @Gert, you cannot use enums directly in an EF database (Oh, drats).
However, an enum
is represented by an int
, so the value can still be stored in the database, by the use of a class.
You will need to create a class in order to store the values in the database, and then you are able to refer to it from the MyModel
class.
Like this:
public enum TypesOfFeature // The enum of features
{
One = 1,
Two = 2,
Three = 3
... // etc.
}
public class Feature // The class to map to a table in your DB
{
public int Id { get; set; }
public TypesOfFeature Type { get; set; }
}
Add a DbSet<Feature>
to your code-first model, so you can access this from your DB. Something like public DbSet<Feature> Features { get; set; }
will do.
It might be a good idea to manually add the values into the database so you know their IDs will match the enum's int
value. *You could do this using AddOrUpdate
in theSeed()
method - then when you need to add more, you could add them beneath*
You would need to return the Feature
s you want, from the DB in order to then assign them to your MyModel.Features
property.
Like so:
Feature featureOne = YourDbContext.Features.Single(x => x.Type == TypesOfFeature.One);
Feature featureTwo = YourDbContext.Features.Single(x => x.Type == TypesOfFeature.Two);
Feature featureThree = YourDbContext.Features.Single(x => x.Type == TypesOfFeature.Three);
Then, in the code, where you're initializing your MyModel
object, you can then initialize the List<Feature>
, passing in the required Feature
objects you pulled out above:
var model = new MyModel
{
Id = 1,
Name = "Test Name",
Points = 2,
Features = new List<Feature>
{
featureOne,
featureTwo,
featureThree
}
}
Obviously, I don't know what values you have in your Feature
enum
, but above is just an example.
Hope this helps! :)