gpt4 book ai didi

带有 linq 的 C# Entity Framework 返回空引用

转载 作者:太空狗 更新时间:2023-10-29 20:21:15 25 4
gpt4 key购买 nike

我对 C# 中的 Entity Framework 有疑问。我有 2 个实体,用户和用户角色。他们通过关系 User *->1 UserRole

每当我在函数中使用这个查询时:

User user = context.User.Where(i => i.id == id).FirstOrDefault();
return user.UserRole.accessLevel;

查询返回用户,但 UserRole 为空。 User表中有roleId,它与UserRole的id相关,虽然UserRole实体为null,但调试时roleId的值是正确的。这很奇怪,因为它以前从未发生过......

我已经确定我在模型和数据库中的关系是正确的。我已将正确的行添加到数据库中。

编辑:

抱歉,我应该提到我使用自定义可测试数据库 Controller :

public class DBController : IUnitOfWork
{
readonly ObjectContext context;
const string ConnectionStringName = "MarketPlaceDBEntities";

public DBController()
{
var connectionString =
ConfigurationManager
.ConnectionStrings[ConnectionStringName]
.ConnectionString;
context = new ObjectContext(connectionString);
}

public void Commit()
{
context.SaveChanges();
}

public IObjectSet<Category> Category
{
get { return context.CreateObjectSet<Category>(); }
}
public IObjectSet<ItemComment> ItemComment
{
get { return context.CreateObjectSet<ItemComment>(); }
}
public IObjectSet<ItemRating> ItemRating
{
get { return context.CreateObjectSet<ItemRating>(); }
}
public IObjectSet<Item> Item
{
get { return context.CreateObjectSet<Item>(); }
}
public IObjectSet<ItemSale> ItemSale
{
get { return context.CreateObjectSet<ItemSale>(); }
}
public IObjectSet<ItemScreenshot> ItemScreenshot
{
get { return context.CreateObjectSet<ItemScreenshot>(); }
}
public IObjectSet<UserRole> UserRole
{
get { return context.CreateObjectSet<UserRole>(); }
}
public IObjectSet<User> User
{
get { return context.CreateObjectSet<User>(); }
}
}

然后我通过它进行操作。也许它与我的概率有关。

interface IUnitOfWork
{
IObjectSet<Category> Category { get; }
IObjectSet<ItemComment> ItemComment { get; }
IObjectSet<ItemRating> ItemRating { get; }
IObjectSet<Item> Item { get; }
IObjectSet<ItemSale> ItemSale { get; }
IObjectSet<ItemScreenshot> ItemScreenshot { get; }
IObjectSet<UserRole> UserRole { get; }
IObjectSet<User> User { get; }
void Commit();
}

我以前有过这整件事,但不知道为什么会出错..

编辑 2:

解决了!感谢 RicoSuter。

在我的数据库 Controller 的构造函数中启用延迟加载解决了这个问题。我以为它已经启用了,因为它在数据库模型中设置为 true,但看起来在创建新上下文时,您必须再次手动启用它。

public DBController()
{
var connectionString =
ConfigurationManager
.ConnectionStrings[ConnectionStringName]
.ConnectionString;
context = new ObjectContext(connectionString);
context.ContextOptions.LazyLoadingEnabled = true;
}

最佳答案

尝试预先加载 UserRole(加入):

context.User.Include("UserRole").Where(i => i.id == id).FirstOrDefault();

或者先启用延迟加载:

context.ContextOptions.LazyLoadingEnabled = true;
context.User.Where(i => i.id == id).FirstOrDefault();

否则与数据库中的 UserRole 没有关系...

关于带有 linq 的 C# Entity Framework 返回空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11628719/

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