How to migrate a class using Generic enums with the Entity Framework Core?

c# entity-framework-core

Question

How would you migrate this Car Class to a database using the Entity Framework?

I have a Main car class (which inherits from a Car Interface Class) with one Generic property called Part

public class Car<Parts> : GenericCarInterface
{
    public Parts Part { get; set; }
}

Then I have several enums representing different parts that can be passed into the Generic Parts property of the Car Class

public enum VokswagenParts
{
    VWWheels,
    VWLights,
    VWEngine
}

public enum TyotaParts
{
    ToyotaSpoiler,
    ToyotaAirFilter,
    ToyotaBrakes
}

public enum FiatParts
{
    FiatExhaust,
    FiatSuspension,
    FiatCVOuter
}

I envisage setting up an ApplicationDbContext as follows but the EF does not know what to make of the Part property

public class ApplicationDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"ConnectionStringHere");
    }

    public DbSet<GenericCarInterface> Cars { get; set; }
}

Any Ideas on the ways that this can be accomplished using Entity Framework Core?

1
0
3/10/2020 8:40:58 AM

Popular Answer

I think i may have figured out a solution.

If i can create a separate class in my repository to hold the enum number values and the enum type names:

public class Car
{
     public Guid CarId { get; set; }
     public Part Part { get; set; }
} 

public class Part
{
    public Guid CarId { get; set; }
    public Guid PartId { get; set; }
    public int Enum { get; set; }
    public string EnumName { get; set; }
}

Then I can persist that standard class to the database then simply re-compile the code back to the original Car class format just before transferring between layers

I might create a separate enum for the part names just to keep it strongly typed but I like the idea of having the names persisted not just enum numbers

0
3/10/2020 11:24:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow