簡體   English   中英

EF Core 中是否有過濾導航單個屬性(不是集合)

[英]Is there anyway in EF Core to Filter Navigation single Property ( not collection )

我有一個場景,我想根據特定條件使用 EF 獲取導航屬性。

  • 如果 isActive=true 則要獲取 Account,否則不獲取 Account。
  • 想發送 isActive=true 然后分享真實記錄; isActive=false 共享虛假記錄。

EF Core可以嗎?

下面是片段。

 return await _context.Contacts
.Include(x => x.PrefixTitle)
.Include(x => x.Account) // **here i want to fetch this if Account.IsActive=true**
.Include(x => x.AssignedToUser)
.Include(x=>x.LeadSource)
.Include(x=>x.EmailAddress.Where(p=>p.IsDeleted==false))                
.Where(a => a.ContactId == id && a.IsDeleted == false)
.FirstOrDefaultAsync();

上面的帳戶是單一導航屬性而不是集合,下面是聯系人和帳戶類以了解詳細信息。

public class Contact
{
public int ContactId { get; set; }
public string Department { get; set; }
public int? AccountId { get; set; }
public Account Account { get; set; } //one-many relation
}

public class Account 
{
public int AccountId { get; set; }
public string Name { get; set; }
public ICollection<Contact> Contacts { get; set; } = new List<Contact>(); // One-Many relation
}

任何幫助將不勝感激。 謝謝

沒有簡單的方法。

Project Contact 以匿名結果並有條件地檢索 Account。 EF 將自動修復聯系人和檢索到的帳戶之間的引用。

然后 select 來自該匿名結果的聯系人:

 var projected = await _context.Contacts
.Include(x => x.PrefixTitle)
// Don't include it here.  Conditionally add it during projection below.
// .Include(x => x.Account) // **here i want to fetch this if Account.IsActive=true**
.Include(x => x.AssignedToUser)
.Include(x=>x.LeadSource)
.Include(x=>x.EmailAddress.Where(p=>p.IsDeleted==false))                
.Where(a => a.ContactId == id && a.IsDeleted == false)
.Select(c => new {
    c,
    // Only retrieve linked account if it is active
    Account = c.Account.IsActive ? c.Account : null
})
.ToListAsync();

// Finally, select the contact from the projection
return projected.Select(c => c.c).FirstOrDefault(); 

暫無
暫無

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

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