繁体   English   中英

如何指定实体框架核心表映射?

[英]How to Specify Entity Framework Core Table Mapping?

我制作了一个简单的实体框架 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

  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<Language>(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<Language>(x => x .ToTable("MyAccountsTable") .Property(entity => entity.PasswordHash) .HasField("MyPasswordHashColumn") ); } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM