如何指定Entity Framework核心表映射?

问题描述 投票:0回答:1

我制作了一个简单的实体框架 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. 假设我在数据库中有一个表

    MyAccounts
    ,我想将其映射到一个实体
    Accounts

  2. 假设我有一列

    password
    ,我希望将其映射到 POCO 属性
    PasswordHash

c# entity-framework asp.net-core entity-framework-core
1个回答
75
投票
  1. 要指定数据库表的名称,可以使用属性或Fluent API:

    使用属性:

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

    使用 Fluent API:

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

    使用属性:

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

    使用 Fluent API:

     public class YourContext : DbContext
     {
         protected override void OnModelCreating(ModelBuilder builder)
         {
             builder.Entity<Account>(x => x
                 .ToTable("MyAccountsTable")
                 .Property(entity => entity.PasswordHash)
                     .HasColumnName("MyPasswordHashColumn")
             );
         }
     }
    
© www.soinside.com 2019 - 2024. All rights reserved.