Question

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).

1
5
7/24/2018 5:03:40 PM

Popular Answer

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.

6
7/24/2018 5:58:32 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