Reputation: 1895
Is it possible to tell Entity Framework via fluent mapping API to add a column to a specific table without a corresponding property in a model class?
Yes, I can achieve that by executing SQL script in a migration, but I would prefer to have this specified in a model configuration rather than in migrations.
Upvotes: 4
Views: 3842
Reputation: 1231
I've been looking into this, admittedly to get around the problem of no native value-object(complex properties) handling until after release of EF core.
Shadow properties are a way of specifying that a migration generated from this context should add a column to the database. Specifically see my example:
// In DbContext-inheriting class:
protected override void OnModelCreating(ModelBuilder builder)
{
// Ignore the model property that holds my valueobject -
// (a complex type encapsulating geolocation latitude/longitude)
var entityBuilder = builder.Entity<Item>()
.Ignore(n => n.Location);
// Add shadow properties that are appended to the table in the DB
entityBuilder.Property<string>("Latitude");
entityBuilder.Property<string>("Longitude");
base.OnModelCreating(builder);
}
This generates the migration table-creation statement as follows:
migrationBuilder.CreateTable(
name: "Items",
columns: table => new
{
Key = table.Column<string>(nullable: false),
Latitude = table.Column<double>(nullable: false),
Longitude = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Items", x => x.Key);
});
Upvotes: 6