简体   繁体   中英

Entity Framework Core using enum as FK

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; }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM