Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

linq - Equivalent to SQL IN clause

I've got an entity called new_trexmail with a string attribute called new_contextline.

I'm trying to get a list of entities where new_contextlineis in a defined list.

The following code fails with the error : NotSupportedException: Invalid 'where' condition. An entity member is invoking an invalid property or method.

string[] test = new[]{"aaa", "hhh"};

var query = from n in New_trexmailSet
            where test.Contains(n.New_contextline)
            select n;

I understand why this error is being thrown but I'm wondering if it's possible to do the equiavalent of an IN clause using XRM.

If it is possible then how do I go about getting XRM to execute SELECT * FROM new_trexmail WHERE new_contextline in ('aaa', 'hhh')?

Thanks,

David

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out the (longer than desired) list of LINQ limitations, particularly the limitation on the where clause:

The left side of the clause must be an attribute name and the right side of the clause must be a value. You cannot set the left side to a constant. Both the sides of the clause cannot be constants. Supports the String functions Contains, StartsWith, EndsWith, and Equals.

So since test isn't a CRM attribute, you can't call Contains on it. However, one way around this is to use "Dynamic Linq" as developed by ScottGu and as demonstrated below:

//must include the below using statements
//using System.Linq;
//using System.Linq.Dynamic;

var trexmailSet = New_trexmailSet;

string[] test = new[] { "aaa", "hhh" };

string whereClause = "";

foreach (string name in test)
{
    whereClause += string.Format("new_contextline = "{0}" OR ", name);
}

trexmailSet = trexmailSet.Where(whereClause.Substring(0, whereClause.Length - 4));

var query = from n in trexmailSet
            select n;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...