Jan*_*las 4 .net c# entity-framework
是否可以通过流畅的映射 API 告诉实体框架将列添加到特定表中,而模型类中没有相应的属性?
是的,我可以通过在迁移中执行 SQL 脚本来实现这一点,但我更愿意在模型配置中而不是在迁移中指定它。
我一直在研究这个问题,无可否认,在 EF 核心发布之前,我一直在解决没有原生值对象(复杂属性)处理的问题。
影子属性是一种指定从此上下文生成的迁移应向数据库添加列的方法。具体看我的例子:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
这将生成迁移表创建语句,如下所示:
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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2473 次 |
| 最近记录: |