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).
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 ValueGeneratedOnAdd
here, 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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With