c# - 更改导航属性的默认列名称

标签 c# asp.net asp.net-core entity-framework-core

我有以下类(class)

public class TreeItem
{
    public long Id { get; set; }
    public Tree Tree { get; set; }
    public string Model { get; set; }
    public string Version { get; protected set; }
    public string Index { get; protected set; }
}

我想更改默认数据库的属性树的列名。作为在数据库中查找“TreeId”列的默认 Entity Framework ,但我们的名称约定表明此列应命名为“tree_id”

如果我尝试将其设置如下:

 modelBuilder.Entity<TreeItem>().Property(t => t.Tree).HasColumnName("tree_id");

Ef 抛出异常消息:

Cannot call Property for the property 'Tree' on entity type 'TreeItem' because it is configured as a navigation property. Property can only be used to configure scalar properties.

是否可以将属性树的默认列名称从“TreeId”更改为“tree_id”?

最佳答案

尝试使用 MapKey():

modelBuilder.Entity<TreeItem>()
            .HasRequired(it => it.Tree)
            .WithMany()
            .Map(m => m.MapKey("tree_id"));

编辑

对于 EF Core,您可能必须使用提到的变通方法 here :

modelBuilder.Entity<TreeItem>()
            .Property<long>("TreeId")
            .HasColumnName("tree_id");

关于c# - 更改导航属性的默认列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091157/

相关文章:

c# - 如何在 EF Core 3.1 中以异步方式使用 GroupBy?

c# - 与 LINQ to XML 合并

c# - 从 shell 元数据属性获取变形视频的显示大小

dependency-injection - .NET Core 依赖注入(inject)实例何时被释放?

c# - 当我使用 Response.Redirect() 或 Server.Transfer() 我的用户被注销

asp.net - 每次按钮都会导致完整的回发,即使是在更新面板中

.net - 是否可以预热应用程序?

c# - 最佳实践 : C# working with DB

c# - 在 C++ 中触发事件并在 C# 中处理它们

javascript - 显示 JSON 返回的错误消息