简体   繁体   English

使用枚举作为 FK 的 Entity Framework Core

[英]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.但是,在我使用迁移创建数据库后,会创建 2 个外键。 Why is it creating it twice?为什么要创建两次?

InterventionStateId
InterventionStateId1

here is code这是代码

on context class在上下文 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根据评论,我会 model 像这样的实体

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.将枚举添加到混合中没有任何用处,因为您必须将它们作为字符串存储在数据库中才能获得您提到的名称,或者存储 int 值,然后您必须继续查找。

You can add the unique constraint to the Name of the Intervention state您可以将唯一约束添加到干预Name state

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

but really no more configuration than this is needed.但实际上不需要更多配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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