简体   繁体   中英

C#, EF: Select from table using list of tuples

Let's assume that I have a List of tuples with 3 properties. Now in my database, I have a Table that has 3 fields that may or may not match up with the tuples. How on earth do I tell EF

"Select from OtherTable o where o.Prop1 = tuple.Item1 && o.Prop2 = tuple.Item2 && o.Prop3 = tuple.Item3".

I understand very well how to do this if I have a single tuple, but I don't know how to do it when I have a list of tuples and I want all the matching records from OtherTable returned. If I was matching on a single property, I would do something like "where ListOfIds.Contains(id)...) and then go about my day but with multiple properties this approach falls apart.

Any help is greatly appreciated.

What about SQL query for entity with dynamic "where" condition?

    var list = new List<Tuple<string, int, bool>>();
    list.Add(new Tuple<string, int, bool>("1", 2, true));
    list.Add(new Tuple<string, int, bool>("2", 4, true));
    list.Add(new Tuple<string, int, bool>("3", 5, false));

    var query = list.Select(x => x.GetType().GetProperties().Select((y, index) => string.Concat("o.Prop", index + 1, "=", y.GetValue(x))).Aggregate((a, b) => a + " and " + b))
                    .Aggregate((a, b) => string.Format("({0}) or ({1})", a, b));

    var result = context.OtherTable.SqlQuery("Select * from OtherTable o where " + query).ToList();

OR you can use Contains that way (as wonderbell said, it will work only if all of your o.Prop N have string type, but you can try to use something like SqlFunctions.StringConvert to cast another type to string):

    var queryList = list.Select(x => x.GetType().GetProperties().ToList().OrderBy(x => x.Name).Select(y => y.GetValue(x).ToString())
                    .Aggregate((a, b) => a + "," + b));
    var result = context.OtherTable.Where(x => queryList.Contains(x.Prop1 + "," + x.Prop2 + "," + x.Prop3))
                    .ToList();   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM