简体   繁体   中英

How to map a field to a differently named column in EF Core 6.0

I am trying to map a field from an entity to a column in a table. I want the column to have a different name to the field.

Entity class:

public class MyEntity
{
    private string _dynamicallyCreatedValue;
}

entity configuration:

    builder.Property<string>("MyColumnName")
           .HasField("_dynamicallyCreatedValue);

migration exception: The specified field '_dynamicallyCreatedValue' cannot be used for the property 'MyColumnName' because it does not match the property name. Entity type properties that aren't associated with a CLR property must match the field name exactly.

Also tried:

builder.Property<string>("_dynamicallyCreatedValue")
       .HasField("_dynamicallyCreatedValue")
       .HasColumnName("MyColumnName");

migration exception: The property '_dynamicallyCreatedValue' cannot be added to the type 'MyEntity' because no property type was specified and there is no corresponding CLR property or field. To add a shadow state property, the property type must be specified.

This works:

    builder.Property<string>("_dynamicallyCreatedValue");

but then I don't get the column name I require.

You can use:

builder
    .Property<string>("_dynamicallyCreatedValue") // Name of field
    .UsePropertyAccessMode(PropertyAccessMode.Field) // Access mode type
    .HasColumnName("MyColumnName"); // Db column name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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