C# 实体框架列名到属性映射dbentry

C# 实体框架列名到属性映射dbentry,c#,entity-framework,entity-framework-core,C#,Entity Framework,Entity Framework Core,我试图在DbContext中保存实体时将实体属性映射到数据库列名,但我不知道如何在EF7中实现 通过迁移生成数据库架构后,列名并不总是与对象中的属性名相同。 例如,下面的对象架构: public class Document { [Key] public int Id { get; set; } public string Name { get; set; } public User Author { get; set; } } 将在数据库中具有Id、名称和

我试图在DbContext中保存实体时将实体属性映射到数据库列名,但我不知道如何在EF7中实现

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

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

    public string Name { get; set; }

    public User Author { get; set; }
}
将在数据库中具有Id、名称和AuthorId列。 接下来,当我迭代EntityEntry属性时,它包含Id、Name和AthorId列。我可以很容易地映射Id和名称
我要寻找的是如何确定EntityEntry中的“AuthorId”映射到文档中的Author字段



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


我在EF6中发现了类似的问题,但它非常复杂,并且使用了EF6特有的类。

根据我的评论,
作者
字段不是简单的对象/结构(即:
日期时间
枚举
,等等),也不是原语(即:
int
字符串
,等等)。因此,它是一个
导航属性
,只存储对象的ID。然后,此ID允许您导航到另一个表中存储
作者
对象复杂数据的行

因此,您需要一个
DbContext
DbSet
s,如下所示:

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; }
}
查询数据库时:

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

Author
字段不是简单的对象/原语,因此被视为导航属性(即:存在于另一个表中的对象的ID)。默认情况下,EF7将在导航属性的名称中添加“Id”,并将其存储为
int
。谢谢您的回答。这(在某种程度上)解决了FK属性的问题,但我仍在寻找解决方案来获得提到的映射。@Tomqaz,你真的不能,db只知道FK和id,其他一切都由ef处理。但是,您知道导航属性+“Id”将是Id键(特别是如果您像我所示那样设置了表)。您可以查看信息架构表并查找fk(即:如果fk存在,您知道它是一个导航属性),这可能会有所帮助?@Tomqaz,我还应该注意,导航属性由更改跟踪程序跟踪(即:如果您更改了作者)。我最近开发了一个类似的ef7历史跟踪器,并遍历了entities属性,其中old value!=当前值。在这个网站上有很多这样的问题。好吧,也许这就足够了。Thx再一次=]
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