【问题标题】:EF Code First: Foreign Key With Where Clause?EF 代码优先:带有 Where 子句的外键?
【发布时间】:2012-08-31 18:43:55
【问题描述】:

给定这样的实体:

public class Entity
{
    public int Id { get; set; }
    public ICollection<EntityTwo> EntityTwos { get; set; }
}

public class EntityTwo
{
    public int Id { get; set; }
    public int TypeId { get; set; }
    public int EntityId { get; set; }
}

通常,Entity.EntityTwos 将返回 EntityId 等于 Entity.Id 的所有 EntityTwo 实体。是否可以装配模型,以便属性返回在该 Id 上加入的实体,但也有 EntityTwo.TypeId == 2(本质上是在加入中添加 where 子句)?

【问题讨论】:

    标签: .net linq entity-framework linq-to-entities ef-code-first


    【解决方案1】:

    您必须进行手动连接,而不是依赖导航属性来创建隐含连接。

    【讨论】:

      【解决方案2】:

      也许你可以通过换一种方式来解决这个问题。您的加入密钥将是:

      { TypeId, Id } equals { 2, Id }
      

      也许可以使用常量作为两个复合键之一?请参阅 Ladislav 的 composite key as foreign key 答案。

      【讨论】:

      • 看起来很有希望,但复合映射需要两个属性(在实体上添加一个具有常量值的属性也不起作用)。这个类似的问题/答案似乎证实了:stackoverflow.com/questions/11526497/…
      猜你喜欢
      • 2018-02-13
      • 2018-05-31
      • 1970-01-01
      • 2012-01-13
      • 2016-01-31
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多