Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadow primary key

I want create a table with a primary key shadowed (out of the model).

public class Person
{
    public string Name { get; set; }
}

public class PersonEntityTypeConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> builder)
    {
        builder.Property?
        builder.HasKey("Id")????
    }
}

Note: the real case is a different class and a value object (DDD).

like image 613
Jhon Duck Avatar asked Jul 24 '18 17:07

Jhon Duck


2 Answers

There are two ways to get this done. One is to define the property and then configure it as key (the order matters)

builder.Property<int>("ID")
    .HasColumnType("int")
    .ValueGeneratedOnAdd();
builder.HasKey("ID");

You probably want ValueGeneratedOnAddhere, because it's more or less the point of shadow properties to do everything under the hood.

I never like code in which the order of statements is a hidden requirement. It may lead to unexpected bugs. I would prefer the single-statement option:

builder.Property<int>("ID")
    .HasColumnType("int")
    .ValueGeneratedOnAdd()
    .HasAnnotation("Key", 0);

The value 0 in HasAnnotation is entered because it's mandatory. It has no bearing on the key generation.

I'm not yet sure if it's a good idea to use shadow properties in keys. I can't oversee which issues may appear when actually working with them. It may be a very good idea indeed.

like image 78
Gert Arnold Avatar answered Oct 11 '22 04:10

Gert Arnold


I don't use the TypeBuilder a lot but this should be close:

public void Configure(EntityTypeBuilder<Person> builder)
{
    builder.Property<int>("id");
    builder.HasKey("Id");
}
like image 3
Henk Holterman Avatar answered Oct 11 '22 05:10

Henk Holterman