EF:自动加载相关数据

时间:2018-07-01 17:51:03

标签: c# entity-framework entity-framework-core

当前,当我要选择具有相关属性的帐户时,每次选择数据时都必须手动添加它们:

public async Task<List<AccountDataModel>> GetAccountsAsync()
{
    return await _dbContext.Accounts.Include(a => a.Settings).ToListAsync();
}

public Task<AccountDataModel> GetAccountByLoginAsync(string login)
{
    return Task.FromResult(_dbContext.Accounts.Include(a => a.Settings).Where(a => a.Login.Equals(login)).FirstOrDefault());
}

数据模型:

public class AccountDataModel
{
    public string Id { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
    public DateTime Created { get; set; }
    public SettingsDataModel Settings { get; set; } = new SettingsDataModel();
} 

public class SettingsDataModel
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public AccountDataModel Account { get; set; }
}

关系设置:

modelBuilder.Entity<AccountDataModel>(e =>
{
    // Set primary key
    e.HasKey(a => a.Id);

    // Settings one-to-one relationship
    e.HasOne(a => a.Settings)
        .WithOne(s => s.Account)
        .OnDelete(DeleteBehavior.Cascade)
        .HasForeignKey<SettingsDataModel>(s => s.Id)
        .IsRequired();
});

我想知道,是否有可能为每个选定的Settings自动加载相关的Account属性?

我正在使用最新版本的EF Core。

0 个答案:

没有答案