我正在使用基本上只包含标准IDbSet集合的基本上代码优先Entity Framework上下文,其中T只是一个POCO类。在我的上下文中,我已禁用延迟加载。虽然我的模型类中有“导航属性”,但我已从它们中删除了virtual关键字。
存储库中的“获取全部”方法会进行一些自定义过滤,以确保当前用户只能查看他们拥有的数据,除非他们是管理员。我遇到了一个特殊问题,即我以管理员身份登录,并且还与某些记录关联。由于我登录的实体加载在上下文中,即使我已禁用了延迟加载、删除了virtual和不使用Include或Load,结果中与我的个人资料有关系的对象仍会自动设置导航属性。
这不是来自我的项目的代码,只是一个示例,说明我正在做的事情的想法。它可能有拼写错误和语法错误。
存储库中的“获取全部”方法会进行一些自定义过滤,以确保当前用户只能查看他们拥有的数据,除非他们是管理员。我遇到了一个特殊问题,即我以管理员身份登录,并且还与某些记录关联。由于我登录的实体加载在上下文中,即使我已禁用了延迟加载、删除了virtual和不使用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;
}
}
所以,上述代码的问题在于,如果我以所有者身份(无论是管理员还是其他身份)运行该代码,则我拥有的那些记录将具有Owner属性设置,而不是null。我希望实体框架离开我的业务,不要自动设置这个属性。这会导致下游出现问题,特别是在以管理员和所有者身份运行代码时,因此您会得到一些Owner = null的记录和一些Owner已设置的记录。这很烦人。请帮我停止它。