实体框架加载相关实体
本文关键字:实体 加载 框架 | 更新日期: 2023-09-27 18:19:58
我使用的是代码优先的实体框架,其基本上下文仅由标准IDbSet集合组成,其中T只是一个POCO类。在我的上下文中,我禁用了延迟加载。虽然我的模型类中有"导航属性",但我已经从中删除了虚拟关键字。
存储库中的"Get All"方法执行一些自定义筛选,以确保当前用户只能看到他们拥有的数据,除非他们是管理员。我以管理员身份登录时遇到了一个特殊的问题,该问题也与某些记录相关。由于我登录的实体是在上下文中加载的,即使我禁用了延迟加载、删除了虚拟加载并且没有使用Include或Load,结果中与我的配置文件关联的对象也会自动设置导航属性。
这不是我项目中的代码,只是一个例子来展示我正在做的事情。它可能有打字错误和语法错误。
public class Record
{
public Guid Id { get; set; }
public string Name { get; set; }
public Owner Owner { get; set; } //No virtual keyword
public Guid OwnerId { get; set; }
}
public class Owner
{
public Guid Id { get; set; }
public string Name { get; set; }
public Collection<Record> Records { get; set; } //No virtual keyword
}
public class Context : DbContext
{
IDbSet<Owner> Owners { get; set; }
IDbSet<Record> Records { get; set; }
public static Context Create()
{
Context context = new Context();
context.Configuration.LazyLoadingEnabled = false; //Lazy loading disabled
return context;
}
}
public class Repository
{
private Context Context { get; set; }
public Owner CurrentOwner { get; private set; }
public Repository()
{
Context = Context.Create();
//Code here to get the application user and look up an associated "owner"
//entity if the user is an "owner" (they could just be an administrator)
//but the GetCurrentOwnerOrNull uses the Context to find the user
CurrentOwner = GetCurrentOwnerOrNull();
}
public IQueryable<Record> GetRecords(bool asAdmin)
{
IQueryable<Record> records = Context.Records; //Not including or loading Owner
if (asAdmin)
{
//Verify that the application user is an admin and throw exception otherwise
}
else
{
if (CurrentOwner == null)
{
//Throw a security exception
}
records = records.Where(r => r.OwnerId == CurrentOwner.Id);
}
return records;
}
}
同样,上面的问题是,如果我以所有者的身份运行该代码,无论是否为管理员,那么我拥有的那些记录将设置所有者属性,而不是null。我希望实体框架脱离我的业务,而不是自动设置它。它会在下游造成问题,尤其是当以管理员和所有者的身份运行代码时,因此您会得到一些owner=null的记录和一些设置了owner的记录。这很烦人。请帮我停下来。
这个错误实际上是一个特性。实体框架将自动连接同一上下文中的关联,即使实体是相互独立加载的。
假设如下:
public class Person
{
public Person()
{
this.Pets = new List<Pet>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Pet> Pets { get; set; }
}
public class Pet
{
public int Id { get; set; }
public string Name { get; set; }
public int PersonId { get; set; }
public virtual Person Owner { get; set; }
}
我们还假设这些是正确关联的DB-First或Attributes/Fluent API code-First。
数据库:
Persons
Id Name
1 Erik Philips
Pets
Id Name PersonId
1 Joe 1
以下是将要发生的事情:
var pet = DbContext.Pets.FirstOrDefault(id => id == 1);
var person = DbContext.Persons.FirstOrDefault(id => id == 1);
Assert.AreEqual(person.Pets.Count(), 1);
Assert.IsNotNull(pet.Person);
Assert.AreEqual(pet.Person, person);
之所以会发生这种情况,是因为上下文将保留其缓存中的对象。如果您不关心这些对象的上下文,则需要使用AsNoTracking()
。