gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:46:19 24 4
gpt4 key购买 nike

我制作了一个简单的 Entity Framework 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

最佳答案

  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)
    .HasColumnName("MyPasswordHashColumn")
    );
    }
    }

关于c# - 如何指定Entity Framework核心表映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42190909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com