簡體   English   中英

通過可選的導航屬性c#EF進行熱切加載

[英]Eager loading with optional navigation property c# EF

我在當前項目中使用緊急加載,在此項目中,我具有可選的導航屬性。 這是模型:

public enum AnswerType
{
    Preset,
    Formula
}

public class Answer: Key
{
    public int QuestionId { get; set; }
    public int? CriteriaId { get; set; }
    [Required] [MaxLength(255)] public string Text { get; set; }
    [Required] public AnswerType Type { get; set; }
    public int Order { get; set; }
    public int Priority { get; set; }
    [MaxLength(2083)] public string Image { get; set; }

    public Criteria Criteria { get; set; }
    public Question Question { get; set; }
    public Scenario Scenario { get; set; }
    public IList<AnswerFormula> Formulas { get; set; }
    public IList<Image> Images { get; set; }
}

因此, Answer可以具有Criteria導航屬性,但也可以為null(可為null的CriteriaId )。 我的“包含”是這樣被抓取的:

public IQueryable<T> List(params string[] includes)
{
  IQueryable<T> source = (IQueryable<T>) this._dbEntitySet;
  if (includes != null)
  {
    foreach (string include in includes)
      source = source.Include<T>(include);
  }
  return source;
}

我想做的是這樣的:

public IQueryable<T> List(params string[] includes)
{
  IQueryable<T> source = (IQueryable<T>) this._dbEntitySet;
  if (includes != null)
  {
    foreach (string include in includes)
      source = source.IncludeExists(include).Include<T>(include);
  }
  return source;
}

因此,如果我這樣調用List方法:

List("Answers.Formulas");

這將起作用,因為我們總是有公式。 但是如果我打電話

List("Answers.Criteria", "Answers.Formulas")

它將拋出此錯誤:

“指定的包含路徑無效。EntityType'Piiick.Data.Answer'沒有聲明名稱為'Criteria,Answers'的導航屬性。”

問題是可為空的條件 因此,我想在嘗試執行包含之前更改生成的SQL以檢查是否為空。

我希望這是有道理的

您通過傳遞單個包含路徑"Answers.Criteria, Answers.Formulas"錯誤地調用了該方法。 逗號分隔的字符串不會被Entity Framework解析為兩個不同的include,而是作為單個項進行解析。 因此,您會收到一條錯誤消息,指出您沒有名為Criteria, Answers的導航屬性Criteria, Answers因為該屬性將路徑分隔了. 只有這樣才能給您這樣一條顯然沒有意義的道路:

"Answers"
  └─ "Criteria, Answers"
    └─ "Formulas"

相反,您需要使用兩個不同的路徑來調用方法,例如:

var query = List("Answers.Criteria", "Answers.Formulas");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM