.NET Core - Entity framework - FindAsync 不 return 相关表

.NET Core - Entity framework - FindAsync does not return related tables

(我找到了这个问题的答案,但其中 none 与我的代码兼容)

_context.Partners.Add(partnerCreation.Partner);
await _context.SaveChangesAsync();
var partner = await _context.Partners.FindAsync(id);

我的模型是这样定义的:

public class Partner
{
    public int? Id { get; set; }
    ...
    public User ModificationUser { get; set; }
    public RetributionPlan retributionPlan { get; set; }
}

我希望 ModificationUserretributionPlan 也能被检索到

感谢您的帮助

您缺少包含语句

var partner = await _context.Partners.Include(p => p.ModificationUser).Include(p => p.retributionPlan).FirstOrDefaultAsync(p => p.Id == id);

如果您需要嵌套字段,请使用 ThenInclude

我也更喜欢将 Id 添加为 属性。 所以你的 class 将是:

public class Partner
{
    public int? Id { get; set; }
    ...
    public User ModificationUser { get; set; }
    public int ModificationUserId { get; set; }
    public int retributionPlanId { get; set; }
    public RetributionPlan retributionPlan { get; set; }
}

所以你可以调用

await _context.Partners.FirstOrDefaultAsync(p => p.Id == id);

await _context.Partners.FirstOrDefaultAsync(p=> p.Id == id).Include(x=>x.ModificationUser);