[英]Filtering on projected property field in LINQ to entities query
下面的LINQ to Entities查詢將執行一個子查詢,並將其結果投影到MyViewModel
。
我正在尋找在SubModel
的Text
屬性中使用myText
字符串變量獲取所有ProjectedModel
對象。
var items = (from t1 in db.MyTable
select new MyModel
{
Id = t1.MyId,
SomeItems = (from s1 in db.MyOtherTable
where s1.LinkedId == t1.Id
select new SubModel
{
Id = s1.Id,
Text = s1.Text
})
}).ToList();
偽代碼如下所示:
string myText = "abc";
items = items where SomeItems.Text contains myText
如果要獲得所有子項都具有給定文本的所有項,那么編寫起來就很容易了:
items = items.Where(item =>
item.SomeItems.Any(subItem => subItem.Text.Contains(myText)));
如果要匹配所有項目,請使用All
。 實際上,您的需求目前尚不完整,因為它們假設只有一個子項目。 (如果您知道總會有一個子項目,則不要使SubItems
成為一個集合,使其成為一個項目,然后在查詢中獲得第一個項目。)
你可以這樣做
item.Where(w => myText.Contains(w.Text));
或者您可以使用.StartsWith()
或.EndsWith()
參考: LIKE
我的答案已經過時,或可能無濟於事,但有些其他事情可能對您有幫助
var selectItedm = (from a in item
where SqlMethods.Like(a.Text,"%"+myText+"%")
select new {a.Id,a.Text}).ToList();
您可以使用更多的SqlMethods
只需包含System.Data.Linq.SqlClient;
SqlMethods
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.