【问题标题】:entity framework column name to property mapping dbentry实体框架列名到属性映射 dbentry
【发布时间】:2016-04-08 02:38:33
【问题描述】:

我正在尝试将实体属性映射到数据库列名称,同时将实体保存在 DbContext 中,但我不知道如何在 EF7 中执行此操作。

在使用迁移生成数据库架构后,列名并不总是与对象中的属性名相同。 例如,下面的对象架构:

public class Document
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public User Author { get; set; }
}

在数据库中会有 IdNameAuthorId 列。 接下来,当我遍历 EntityEntry 属性时,它包含 Id、Name 和 AthorId 列。我可以轻松地映射 Id 和 Name。
我正在寻找的是如何确定 EntityEntry 中的“AuthorId”映射到 Document 中的 Author 字段?



背景:我正在实现通用对象版本历史记录机制,该机制将从 EntityEntries 获取修改的列(来自 SaveChanges 中的 ChangeTracker () in DbContext) 并保存适当的列和它的新值。接下来,在恢复对象时,它应该能够将这些更改映射到适当的实体字段。

我为 EF6 Where does Entity Framework store the mapping between property names and the columns it selects in SQL? 找到了类似的问题,但它非常复杂,并且使用了 EF6 特有的类。

【问题讨论】:

  • Author 字段不是简单的对象/基元,因此被视为导航属性(IE:存在于另一个表中的对象的 ID)。默认情况下,EF7 会将“Id”添加到导航属性的名称中,并将其存储为 int

标签: c# entity-framework entity-framework-core


【解决方案1】:

根据我的评论,Author 字段不是简单的对象/结构(IE:DateTimeEnum 等),也不是原语(IE:intstring 等)。因此,它是一个Navigation Property,并且只存储对象的 ID。然后,此 ID 允许您导航到另一个表中存储Author 对象的复杂数据的行。

因此,您可能需要DbContextDbSets:

public class Document {
    public int Id { get; set; } // No need for [Key] ID is auto detected
    public string Name { get; set; }

    // Foreign Keys
    public int AuthorId { get; set; } // Can use "int?" if you want to allow it to be nullable
    public User Author { get; set; }
}

public class Author {
    public int Id { get; set; }
    public string Name { get; set; }
}

public class BookContext : DbContext {
    public DbSet<Author> Authors { get; set; }
    public DbSet<Document> Documents { get; set; }
}

这将产生表格:

Document: Id (int), Name (nvarchar), AuthorId (int) with FK to Author table
Author:   Id (int), Name (nvarchar)

查询数据库时:

var books = BookContext.Documents // Access documents table
                 .Include(q => q.Author) // Ensure that the author's properties are loaded, not just the ID
                 .Where(q => q.Name.Contains("SomeText")) // Search for documents with a name matching this text

【讨论】:

  • 感谢您的回答。这(以某种方式)解决了 FK 属性的问题,但我仍在寻找获得提及映射的解决方案。
  • @Tomqaz,你真的不能,db只知道fk和id,其他一切都由ef处理。但是,您确实知道,导航属性 +“Id”将是 id 键(特别是如果您像我展示的那样设置表格)。您可以查看信息架构表并查找 fk(即:如果 fk 存在,您知道它是导航属性),这可能会有所帮助吗?
  • @Tomqaz,我还应该注意,导航属性由更改跟踪器跟踪(即:如果您更改作者)。我最近开发了一个类似的 ef7 历史跟踪器,并遍历了旧值!= 当前值的实体属性。此网站上有许多问题详细说明。
  • 好吧,也许这就够了。多谢一次 =]
猜你喜欢
  • 2015-01-22
  • 2023-03-20
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
相关资源
最近更新 更多