【问题标题】:How to Specify Entity Framework Core Table Mapping?如何指定实体框架核心表映射?
【发布时间】:2017-06-30 15:54:04
【问题描述】:

我制作了一个简单的实体框架 ASP 核心应用程序,但我不知道为什么:

我做了一个这样的上下文:

public class AstootContext : DbContext
{
    public AstootContext(DbContextOptions<AstootContext> options)
        : base(options)
    { }

    public DbSet<Account> Accounts { get; set; }
    public DbSet<User> Users { get; set; }
}

我有两张表,模型如下:

public class Account
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string PasswordHash { get; set; }
    public DateTime Created { get; set; }

    List<User> Users { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public DateTime Birthday { get; set; }
    public Account Account { get; set; }
}

有趣的是,当我运行我的应用程序时,它实际上可以获取数据。这看起来很奇怪,因为我没有指定任何表映射。 我假设这只是自动映射,因为指定的表名称相同。

我的问题是:

  1. 如果我不希望我的模型名称与数据库完全相同,如何指定表显式表映射?

  2. 如何指定自定义列映射。

  3. 我必须为主键/外键指定什么特别的东西

编辑

澄清

  1. 假设我在 DB MyAccounts 中有一个表,我想将其映射到实体 Accounts

  2. 假设我有一个列 password,我希望将其映射到 POCO 属性 PasswordHash

【问题讨论】:

  • 你有一堆问题,你真的应该只问一个。
  • @DavidG 它们都与特定的映射有关,未来的用户只需要去一个问题就可以找到一个很好的完整答案,如果需要,我会悬赏
  • 问题 2 是什么意思,您要命名列吗?
  • 我在数据库中的列被命名为密码,但它在模型中被命名为密码哈希,我无法想象实体框架可以自动解决这个问题,我如何将该属性指向列
  • EF 不可能重命名您的密码列,您确定没有代码为您执行此操作吗?您未显示的任何属性或上下文设置?

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


【解决方案1】:
  1. 要指定数据库表的名称,可以使用属性或fluent API:

    使用属性:

     [Table("MyAccountsTable")]
     public class Account
     {
          public string PasswordHash { get; set; }
     }
    

    使用流畅的 API:

     public class YourContext : DbContext
     {
         protected override void OnModelCreating(ModelBuilder builder)
         {
             builder.Entity<Language>(entity => {
                 entity.ToTable("MyAccountsTable");
             });
         }
     }
    
  2. 手动命名你的列,它非常相似,你可以使用属性或流畅的 API:

    使用属性:

     public class Account
     {
         [Column("MyPasswordHashColumn")]
         public string PasswordHash { get; set; }
    
     }
    

    使用流畅的 API:

     public class YourContext : DbContext
     {
         protected override void OnModelCreating(ModelBuilder builder)
         {
             builder.Entity<Language>(x => x
                 .ToTable("MyAccountsTable")
                 .Property(entity => entity.PasswordHash)
                     .HasColumnName("MyPasswordHashColumn")
             );
         }
     }
    

【讨论】:

  • 谢谢,这太完美了,你碰巧有一个链接到文档中的位置,它指定了将模型名称同步到数据库的自动魔术方式
  • 您可以在herehere 中看到有关列名的部分内容。
  • Table 属性似乎不再起作用。没有 DbSet 名称。我可以实现自定义名称的唯一方法是构建器上的流利的 api。 (从 .NET Core 3 Preview 5 开始)
  • @g.pickardou 好吧,我不打算评论仅处于预览阶段的内容,等平台稳定一些后再回来。
  • @DavidG 稳定了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 2021-07-26
  • 2014-04-01
  • 2021-01-10
  • 2010-10-09
相关资源
最近更新 更多