c# - Entity Framework : Create database column without property in model class

标签 c# .net entity-framework

是否可以通过流畅的映射 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/

相关文章:

c# - 如何使用 Moq 和 C# 模拟 SingleOrDefault()

c# - 关于 catch block 中 catch 语句顺序的问题 - 特定于编译器或语言标准?

.net - 在 Framework 4.0 项目中使用 .NET Framework 4.5 dll

c# - 字符串插值不适用于 .NET Framework 4.6

.net - 如何创建/更新可能存在或不存在的 XML 节点?

LINQ:将 Guid 转换为字符串

c# - 将 32 个 bool 值的集合转换为 32 位整数

c# - 获取LUIS的查询结果

entity-framework - Entity Framework 6 Table-per-Type 继承映射为类型留下鉴别器值(未定义)

entity-framework - 是否有 Entity Framework 的内存提供程序?