【问题标题】:EF 6 Code First storing an entity Reference to specific child in a one of the collections on the entityEF 6 Code First 存储实体对实体集合之一中特定子项的引用
【发布时间】:2017-07-31 16:10:03
【问题描述】:

我有一个域模型,该模型具有以正常的一对多关系配置的实体集合,但是我想在该模型中使用 FK 存储对该集合中特定项目的引用

模型中定义的列表

public ICollection<SLWOUpdate> Updates { get; set; }

对列表中特定项目的引用

public int? SLWOUpdateId { get; set; }
[ForeignKey("SLWOUpdateId")]
public virtual SLWOUpdate LastUpdate { get; set; }

当然,代码负责更新特定项目,而不是让 EF 来做。

这种关系可以在 EF 中配置吗?

我想这样做的原因是为了查询过滤目的,作为必须作为一个语句执行的复杂查询的一部分

【问题讨论】:

  • 您可以像这样构建您的模型,Entity Framework 将不会自动将 LastUpdate 设为最后一次更新(任何时候您将 SLWOUpdate 添加到 Updates 属性对于父母,您必须手动更新LastUpdate(或构建某种方便的方法来做到这一点)。
  • 在将 SLWOUpdate 实体添加到集合中时,我会手动更新它,它会一直工作,直到拉动实体及其更新集合为止。EF 抱怨在名为 SLWOUpdate_Id 的 SLWOUpdate 实体上需要一个 Fk。

标签: entity-framework c#-4.0 ef-code-first


【解决方案1】:

最终添加了一个新的域模型来表示 LastUpdate,它只包含该实体的主键和 LastUpdate 的 FK

表示上次更新的新领域模型

public virtual SLCurrentWOUpdate LastUpdate { get; set; }

public class SLCurrentWOUpdate
{

    [Key]
    public int SLWorkOrder_Id { get; set; }

    public SLWorkOrder SLWorkOrder { get; set; }

    public int? SLWOUpdateId { get; set; }
    [ForeignKey("SLWOUpdateId")]
    public SLWOUpdate SLWOUpdate { get; set; }

}

我可以将其作为一组更大更复杂的谓词的一部分进行查询...我只需要更深入地参考模型:

db.SLWorkOrders
.Where(t => t.TAutoDeclined != null && t.TClosedPendingPayment != null)
.Where(t => t.LastUpdate.SLWOUpdate.UpdateStatusType.SystemName == "CHANGE_PRIORITY");

感觉有点hackish..但它有效..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多