实体框架:在模型类中创建没有属性的数据库列

Jan*_*las 4 .net c# entity-framework

是否可以通过流畅的映射 API 告诉实体框架将列添加到特定表中,而模型类中没有相应的属性?

是的,我可以通过在迁移中执行 SQL 脚本来实现这一点,但我更愿意在模型配置中而不是在迁移中指定它。

Ben*_*min 6

我一直在研究这个问题,无可否认,在 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)

  • +1 对于 EF Core 的解决方案,虽然无法接受您的答案,因为我正在寻找 EF 6.1.3 的解决方案。但是,感谢您发布此信息 - 在切换到 EF Core 时我肯定会使用它。 (2认同)