gpt4 book ai didi

entity-framework - 在 Entity Framework 核心中选择不加载导航属性后包含

转载 作者:行者123 更新时间:2023-12-04 17:44:16 25 4
gpt4 key购买 nike

我使用 Entity Framework 核心 1.1。

我有一个像下面这样的查询,我希望拥有 UserProfile 的用户使用 Include 加载 UserProfile。
但是这个查询总是返回 UserProfile null 。

询问:

var user = dbContext.UserMappers
.Where(e => e.OldUserId == id)
.Select(e => e.User)
.Include(e=>e.UserProfile)
.FirstOrDefault();

楷模:
public class UserMapper
{
[Key, ForeignKey(nameof(User))]
public string UserId { get; set; }
public User User { get; set; }
public int OldUserId { get; set; }
}

public class User : IdentityUser
{
public bool Suspended { get; set; }
public string Nickname { get; set; }
public virtual UserProfile UserProfile { get; set; }
}

public class UserProfile
{
[Key, ForeignKey(nameof(User))]
public string UserId { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public string Telephone { get; set; }
}

最佳答案

来自 EF Core 文档 - Loading Related Data - 忽略包括 部分(重点是我的):

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored.



这与 EF6 不同,其中 Include适用于最终查询实体类型。我不知道这是当前限制还是“设计使然”,但现在您必须从需要包含的实体开始查询。

在你的情况下,它应该是这样的:
var user = dbContext.Users
// if you don't have inverse navigation property
.Where(e => dbContext.UserMappers.Any(um => um.UserId == e.Id && um.OldUserId == id))
// if you have inverse collection navigation property
//.Where(e => e.UserMappers.Any(um.OldUserId == id))
// if you have inverse reference navigation property
//.Where(e => e.UserMapper.OldUserId == id)
.Include(e => e.UserProfile)
.FirstOrDefault();

关于entity-framework - 在 Entity Framework 核心中选择不加载导航属性后包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712908/

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