Azarah
Azarah

Reputation: 1

How to add foreign key that references table without C# model

I wanted to create migration with ef migrations add, all my migrations are written with fluent api but I came across a problem.

How to properly store enum values in the database?

Best option would be to create new table with Id and Name (enum). It would look something like this:

public enum EngineType
{
    Steam = 1,
    Gasoline = 2,
}

----------------------------------------------

modelBuilder.Entity("EngineType", builder =>
{
    builder.ToTable("DIC_ENGINE_TYPES");
            
    builder.Property<int>("Id")
        .HasColumnName("ID")
        .IsRequired();
    builder.HasKey("ID");

    builder.Property<string>("Name")
        .HasColumnName("NAME")
        .HasMaxLength(50)
        .IsUnicode(false)
        .IsRequired();

    builder.HasIndex("Name")
        .IsUnique();
            
    foreach (var enumValue in Enum.GetValues<EngineType>())
    {
        builder.HasData(new { Id = (int)enumValue, Name = enumValue.ToString() });
    }
});

This works fine however I don't know how to add foreign key relationship in my other entities.

For example I want to create an Engines table with column ENGINE_TYPE_ID that references DIC_ENGINE_TYPES:

public class Engine
{
    public int Id { get; set; }
    public EngineType EngineType { get; set; }
}

----------------------------------------------

modelBuilder.Entity<Engine>(builder =>
{
    builder.ToTable("ENGINES");
    builder.Property(x => x.Id)
        .HasColumnName("ID")
        .UseIdentityColumn()
        .IsRequired();

    builder.Property(x => x.EngineType)
        .HasColumnName("ENGINE_TYPE_ID")
        .IsRequired();

    // TODO: add constraint to EngineType, HasOne doesn't work
});

I know that I could write migration manually but is there a way to do add this shadow constraint with fluent api?

Upvotes: 0

Views: 50

Answers (0)

Related Questions