[英]Entity Framework: Create database column without property in model class
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? 是否可以通过流畅的映射API告诉Entity Framework将列添加到特定的表而没有模型类中的相应属性?
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. 是的,我可以通过在迁移中执行SQL脚本来实现这一点,但我更希望在模型配置中而不是在迁移中指定它。
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. 我一直在研究这个问题,不可否认的是,在EF核心版本发布之前解决了没有本机价值对象(复杂属性)处理的问题。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.