簡體   English   中英

如何在Entity Framework Code First中使用字符串主鍵延遲加載子對象?

[英]How to Lazy Load child object with string primary key in Entity Framework Code First?

我有一個對象User ,它引用對象State 外鍵是一個StateID string ,是可選的。 不需要用戶引用State 我的類定義如下

public class User
{
    public int UserID {get; set'}
    public string StateID {get; set;}
    //some other properties

    public virtual State State {get; set;}
}


public class State
{
    public string StateID {get; set;}
    //other properties

    public ICollection<User> Users {get; set;}
}

當我嘗試執行linq查詢以獲取某些用戶及其狀態時, State對象始終為null。 我當然得到了我的用戶的StateID,所以我知道設置正確。

我的查詢如下所示:

var users = userRepo.where(x => x.StateID != null);

還嘗試添加.ToList()以使要執行的延遲加載不起作用。

我曾嘗試添加[key]注釋StateIDState沒有運氣。

我也嘗試放棄延遲加載並在我的查詢中使用include("State")也沒有運氣。

關於我在做什么錯的任何線索?

UPDATE我也試圖明確指定映射,如下所示:

modelBuilder.Entity<User>()
  .HasOptional(t => t.State)
  .WithMany(b => b.Users)
  .HasForeignKey(t => t.StateID);

確保在User類中正確定義了導航屬性。 如下所示:

   public class User
    {
        public int UserID {get; set;}          
        public string StateID {get; set;}

        //some other properties
        public State State {get; set;}
    }

然后,您可以使用Include創建查詢,如下所示:

var users = userRepo.Where(i => i.StateID != null).Include("State").ToList();

更新:

如果要使用延遲加載來實現此目的,請將虛擬鍵盤輸入添加到所有導航屬性。

public class User
{
    public int UserID {get; set;}
    public string StateID {get; set;}
    public virtual State State{get; set;}
}

public class State
{
    public string StateID {get; set;}
    public string StateName { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

還要確保您沒有在DbContext類中禁用延遲加載,如下所示:

this.Configuration.LazyLoadingEnabled = false; // disable Lazy loading

按照上述步驟,延遲加載應該可以工作,下面是一個示例:

在您的操作方法中:

   ViewBag.Result = userRepo.Users.Where(i => i.StateID != null);

在您看來

    @foreach (User item in @ViewBag.Result)
    {
        <div>@item.State.SomePropertyName</div>
    }

暫無
暫無

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

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