如何使Entity Framework返回与某些默认值相关的对象? [英] How can I have Entity Framework return related objects with some defaults?
问题描述
public class Project
{
public int ID {get;组; }
public string Name {get;组; }
public virtual ICollection< Task>任务{get;组; }
}
public class Task
{
public int ID {get;组; }
public string Name {get;组; }
public int ProjectId {get;组; }
public bool IsDeleted {get; set;}
public virtual Project Project {get;组;
}
说我有
public void SomeAction()
{
项目p = repository.GetById(1);
var tasks = p.Tasks;
// var tasks = p.Tasks.Where(t => t.IsDeleted == false);
}
我希望Project类中的Tasks属性将始终执行该过滤器在IsDeleted,只是返回该子集...以避免不得不在该地方写这个条件...
任何建议?
编辑:
我使用EF Code First
EF Code first = NO WAY。只有一个来自EDMX可用的长功能列表,并且完全缺少代码。来自EDMX的映射条件是这样的,但它仍然是有问题的,因为它是硬编码的,不能被更改(=即使你想要,除非你使用另一个EDMX,你永远无法加载删除的实体)。解决方案是在EF中实现全局过滤器,但EF没有任何类似的东西,尽管旧的Linq到实体至少具有关系( DataLoadOptions.AssociateWith
)。
在不需要加载删除的实体到您的应用程序以及在应用程序的内存中进行过滤的情况下,您无法使用热切或懒惰加载的关系更加痛苦。 >
Say I have Project and Task EF Code first classes
public class Project
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}
public class Task
{
public int ID { get; set; }
public string Name { get; set; }
public int ProjectId { get; set; }
public bool IsDeleted {get; set;}
public virtual Project Project { get; set; }
}
Say I have
public void SomeAction()
{
Project p= repository.GetById(1);
var tasks = p.Tasks;
//var tasks = p.Tasks.Where(t=>t.IsDeleted==false);
}
I would like that my Tasks property on the Project class will always perform that filter on IsDeleted and just return that subset ... to avoid having to write that condition all over the place...
Any recommendations?
Edit:
Im using EF Code First
EF Code first = NO WAY. Just one from long list of features which is available in EDMX and it is completely missing in code first. Mapped condition from EDMX does this but it is still problematic because it is hardcoded and cannot be changed (= you will never be able to load deleted entities even if you want to unless you use another EDMX). The solution would be implementation of global filters in EF but EF doesn't have anything like that despite the fact that old Linq-to-entities have them at least for relations (DataLoadOptions.AssociateWith
).
This is much more painful in relations where you cannot use eager or lazy loading without loading deleted entities to your application as well and do filtering in your application's memory.
这篇关于如何使Entity Framework返回与某些默认值相关的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!