实体框架过滤的导航属性 [英] Entity Framework Filtered Navigation Properties

查看:138
本文介绍了实体框架过滤的导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有没有办法使用EF6 /代码首先设置导航属性的过滤器?我想要实现类似于下面的内容,其中Farm.Pigs返回类型等于pig的动物的集合(但不将数据库首先从数据库中加载,而不是将它们存储在单独的表中)。这是可能吗?

  public class Farm {
public int Id {get;组; }

public virtual ICollection< Animal>猪{get;组; }

public virtual ICollection< Animal>奶牛{get;组; }
}

public class Animal {
public int Id {get;组; }

public int FarmId? {get;组; }

public virtual Farm Farm {get;组; }

public string Name {get;组; }
}

public enum AnimalType {
Pig,Cow
}



更新



将更新移动到一个新问题:实体框架一个多TPH映射

解决方案

你不能按照您的要求执行此操作,它是实体框架的当前限制。



如果创建了继承关系,您可以以不同的方式实现,例如

  public class Animal {
public int Id {get;组; }

public AnimalType Type {get;组; }

public string Name {get;组; }
}

public class Pig:Animal {...}

public class Cow:Animal {...}

然后,您可以按照以下文章配置Table per Hierarchy(TPH):



http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first -ctp5-part-1-table-per-hierarchy-tph.aspx


Is there a way to set a filter on a navigation property using EF6/code first?

I want to achieve something similar to the below, where Farm.Pigs returns a collection of animals whose type is equal to pig (but without loading the whole collection from the database first - and not storing them in a separate table). Is this possible?

public class Farm {
    public int Id { get; set; }

    public virtual ICollection<Animal> Pigs { get; set; }

    public virtual ICollection<Animal> Cows { get; set; }
}

public class Animal {
    public int Id { get; set; }

    public int FarmId? { get; set; }

    public virtual Farm Farm { get; set; }

    public string Name { get; set; }
}

public enum AnimalType {
    Pig, Cow
}

Update

Moved the update to a new question: Entity Framework One-Many TPH Mapping

解决方案

You can't do this in the way you asked, it is a current limitation of entity framework.

You could achieve it a different way if you created an inheritance relationship, i.e.

public class Animal {
    public int Id { get; set; }

    public AnimalType Type { get; set; }

    public string Name { get; set; }
}

public class Pig : Animal { ... }

public class Cow : Animal { ... }

You could then configure Table per Hierarchy (TPH) as in the following article:

http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx

这篇关于实体框架过滤的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆