Entity Framework Core using enum as FK

asp.net-core c# entity-framework-core

Question

I want to have a relation between these 2 classes using an enum. However after i create database with migration, 2 foreign keys are created. Why is it creating it twice?

InterventionStateId
InterventionStateId1

here is code

on context class

        modelBuilder.Entity<Intervention>()
          .Property(i => i.InterventionStateId)
          .HasConversion<int>();

        modelBuilder.Entity<Intervention>()
           .HasOne(i => i.InterventionState)
           .WithMany()
           .HasForeignKey(i => i.InterventionStateId);

and the entities

public class Intervention
{
    public Intervention()
    {
        InterventionStateId = InterventionStates.PendingValidation;
    }

    public int Id { get; set; }
    public string Description { get; set; }
    public InterventionStates InterventionStateId { get; set; }
    public InterventionState InterventionState { get; set; }
}


public enum InterventionStates
{
    PendingValidation = 1,
    PendingStatus = 2,
    Closed = 3
}

[Table("hInterventionStates")]
public class InterventionState
{
    [Key]
    public InterventionStates Id { get; set; }
    public string Name { get; set; }

    public ICollection<Intervention> Interventions { get; set; }

}
1
1
11/14/2019 2:18:33 PM

Popular Answer

Based on the comments I would model the entities like so

public class Intervention
{
    public int Id { get; set; }
    public string Description { get; set; }
    public int InterventionStateId { get; set; }
    public virtual InterventionState InterventionState { get; set; }
}

public class InterventionState
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Intervention> Interventions { get; set; }

}

Adding enums to the mix avails nothing here, as you either have to store them in the db as strings in order to get the name as you mentioned, or store the int value, which you then have to proceed to lookup.

You can add the unique constraint to the Name of the Intervention state

modelBuilder<InterventionState>()
    .HasIndex(e => e.Name)
    .IsUnique();

but really no more configuration than this is needed.

2
11/14/2019 3:06:16 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