是否可以通过流畅的映射 API 告诉 Entity Framework 将列添加到模型类中没有相应属性的特定表?
是的,我可以通过在迁移中执行 SQL 脚本来实现这一点,但我更愿意在模型配置中而不是在迁移中指定它。
最佳答案
我一直在研究这个问题,诚然是为了解决在 EF 核心发布之前没有本地值对象(复杂属性)处理的问题。
Shadow properties是一种指定从此上下文生成的迁移应向数据库添加列的方法。具体看我的例子:
// 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);
}
这会生成迁移表创建语句,如下所示:
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);
});
关于c# - Entity Framework : Create database column without property in model class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32560115/