Return 来自第二个 table 的下拉字符串

Return dropdown string from second table

我有两个 table 需要加入我的 Razor 页面视图。第一个 table 称为 'Account' 包含一个状态为 int 的帐户记录。第二个 table 称为 'AccountStatuses' 包含帐户的可能状态。脚手架在Account\Index.cshtml.cs

中创建了以下代码
    public IList<Account> Account { get;set; }

    public async Task OnGetAsync()
    {
        Account = await _context.Account.ToListAsync();
    }

帐户 table 包含一个列 "Status",它对应于帐户状态 table 中的列 "Value"。我想加入这些和 return 列 "StatusString" 从 AccountStatus table 到视图。

您不必连接两个表来获取值。如果您正确设置了您的模型,您可以让 Entity Framework 为您完成工作。我将举例说明如何创建模型。首先,我们有两个模型:

public class Account
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int AccountID { get; set; }

    public string AccountName { get; set; }

    public int AccountStatusID { get; set; }
    [ForeignKey("AccountStatusID")]
    public virtual AccountStatus AccountStatus { get; set; }
}


public class AccountStatus
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int AccountStatusID { get; set; }

    public string AccountStatusName { get; set; }

    public virtual ICollection<Account> Accounts { get; set; }
}

Account 模型具有 属性 AccountStatusID,它将包含状态 ID。我们还为 AccountStatus 模型定义了一个虚拟的 属性。当我们从 Entity Framework.

请求时,EntityFramework 会自动加载它

我们对 AccountStatus 模型做了类似的事情,但在这个模型中,我们将有一个虚拟的 Account 模型集合。

现在我们必须定义我们的 ApplicationDbContext class,它可能是以下内容:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

    public DbSet<Account> Accounts { get; set; }
    public DbSet<AccountStatus> AccountStatuses { get; set; }
}

现在我们可以执行以下查询:

// Get the account by id
Account account1 = await _context.Accounts.SingleOrDefaultAsync(m => m.AccountID == id);

// Get the account by id including the Account status
Account account2 = await _context.Accounts.Include(m => m.AccountStatus).SingleOrDefaultAsync(m => m.AccountID == id);
// account2.AccountStatus contains the AccountStatus
string AccountStatusName = account2.AccountStatus.AccountStatusName;


// Get teh account status by id
AccountStatus AccountStatus1 = await _context.AccountStatuses.SingleOrDefaultAsync(m => m.AccountStatusID == id);

// Get the account status by id include the accounts
AccountStatus AccountStatus2 = await _context.AccountStatuses.Include(m => m.Accounts).SingleOrDefaultAsync(m => m.AccountStatusID == id);
// AccountStatus2.Accounts contain all the accounts which has be set to be equal to the current account status
foreach (var account in AccountStatus2.Accounts)
{
    string AccountName = account.AccountName;
}

希望对你有所帮助