Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6226941
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T09:07:31+00:00 2026-05-24T09:07:31+00:00

I have a function called CreateCriteriaExpression that takes a json string and creates a

  • 0

I have a function called “CreateCriteriaExpression” that takes a json string and creates a linq expression from it.

This method is called by another called “GetByCriteria”, which calls the “CreateCriteriaExpression” method and then executes that expression against an entity framework context.

For all of my entity framework objects, the “GetByCriteria” method is identical except for it’s types. So I am trying to convert it to use generics instead of hard coded types.

When the “GetByCriteria” method gets to the point that it has to call the “CreateCriteriaExpression” method, I am having it use a factory class to determine the appropriate class/method to use. Then in the “linq expression” class, the linq expression for a particular type is created and returned.

The problem I am having is that the linq expression has to be created for a specific type, but the return value is of the generic type and it won’t automatically convert between the two, even though the one is a parent of the other (covariance).

Is there any way I can make this work?

Some example code:

The “GetByCriteria” method:

/// <summary>
    /// Gets a <see cref="System.Collections.Generic.List"/> of <see cref="TEntity"/>
    /// objects that match the passed JSON string.
    /// </summary>
    /// <param name="myCriteria">A list of JSON strings containing a key/value pair of "parameterNames" and "parameterValues".</param>
    /// <param name="myMatchMethod">Defines which matching method to use when finding matches on the <paramref name="myCriteria"/>.</param>
    /// <returns>
    /// A <see cref="System.Collections.Generic.List"/> of <see cref="TEntity"/>
    /// objects.
    /// </returns>
    /// <seealso cref="TEntity"/>
    ///   
    /// <seealso cref="Common.MultipleCriteriaMatchMethod"/>
    /// <remarks>
    /// This method takes a <see cref="System.Collections.Generic.List"/> of JSON strings, and a <see cref="Common.MultipleCriteriaMatchMethod"/> and returns a
    /// <see cref="System.Collections.Generic.List"/> of all matching
    /// <see cref="TEntity"/> objects from the back-end database.  The <paramref name="myMatchMethod"/> is used to determine how to match when multiple <paramref name="myCriteria"/> are passed.  You can require that any results must match on ALL the passed JSON criteria, or on ANY of the passed criteria.  This is essentially an "AND" versus and "OR" comparison.
    /// </remarks>
    [ContractVerification(true)]
    public static List<TEntity> GetByCriteria<TContext, TEntity>(List<string> myCriteria, Common.MultipleCriteriaMatchMethod myMatchMethod)
        where TContext : System.Data.Objects.ObjectContext, new()
        where TEntity : System.Data.Objects.DataClasses.EntityObject
    {
        // Setup Contracts
        Contract.Requires(myCriteria != null);

        TContext db = new TContext();


        // Intialize return variable
        List<TEntity> result = null;

        // Initialize working variables
        // Set the predicates to True by default (for "AND" matches)
        var predicate = PredicateBuilder.True<TEntity>();
        var customPropertiesPredicate = PredicateBuilder.True<TEntity>();

        // Set the  predicates to Falase by default (for "OR" matches)
        if (myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAny)
        {
            predicate = PredicateBuilder.False<TEntity>();
            customPropertiesPredicate = PredicateBuilder.False<TEntity>();
        }


        // Loop over each Criteria object in the passed list of criteria
        foreach (string x in myCriteria)
        {
            // Set the Criteria to local scope (sometimes there are scope problems with LINQ)
            string item = x;
            if (item != null)
            {
                JsonLinqParser parser = JsonLinqParserFactory.GetParser(typeof(TEntity));

                // If the designated MultipleCriteriaMatchMethod is "MatchOnAll" then use "AND" statements
                if (myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAll)
                {
                    predicate = predicate.Expand().And<TEntity>(parser.CreateCriteriaExpression<TEntity>(item).Expand());
                    customPropertiesPredicate = customPropertiesPredicate.Expand().And<TEntity>(parser.CreateCriteriaExpressionForCustomProperties<TEntity>(item).Expand());
                }
                // If the designated MultipleCriteriaMatchMethod is "MatchOnAny" then use "OR" statements
                else if (myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAny)
                {
                    predicate = predicate.Expand().Or<TEntity>(parser.CreateCriteriaExpression<TEntity>(item).Expand());
                    customPropertiesPredicate = customPropertiesPredicate.Expand().Or<TEntity>(parser.CreateCriteriaExpressionForCustomProperties<TEntity>(item).Expand());
                }
            }
        }

        // Set a temporary var to hold the results
        List<TEntity> qry = null;

        // Set some Contract Assumptions to waive Static Contract warnings on build
        Contract.Assume(predicate != null);
        Contract.Assume(customPropertiesPredicate != null);


        // Run the query against the backend database
        qry = db.CreateObjectSet<TEntity>().AsExpandable<TEntity>().Where<TEntity>(predicate).ToList<TEntity>();
        //qry = db.CreateObjectSet<TEntity>().Where(predicate).ToList<TEntity>();
        // Run the query for custom properties against the resultset obtained from the database
        qry = qry.Where<TEntity>(customPropertiesPredicate.Compile()).ToList<TEntity>();

        // Verify that there are results
        if (qry != null && qry.Count != 0)
        {
            result = qry;
        }

        // Return the results
        return result;
    }

The JsonLinqParser class (does not build):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinqKit;
using Newtonsoft.Json.Linq;

namespace DAL
{
    internal class JsonLinqParser_Paser : JsonLinqParser
    {
        internal override System.Linq.Expressions.Expression<Func<TEntity, bool>> CreateCriteriaExpression<TEntity>(string myCriteria)
        {
            var predicate = PredicateBuilder.True<BestAvailableFIP>();

            JObject o = JObject.Parse(myCriteria);

            // bmp
            decimal _bmp;
            if (o["bmp"] != null && decimal.TryParse((string)o["bmp"], out _bmp))
            {
                predicate = predicate.And<BestAvailableFIP>(x => x.bmp == _bmp);
            }
            // COUNTY
            if (!string.IsNullOrWhiteSpace((string)o["COUNTY"]))
            {
                string _myStringValue = (string)o["COUNTY"];
                predicate = predicate.And<BestAvailableFIP>(x => x.COUNTY.Contains(_myStringValue));
            }
            // emp
            decimal _emp;
            if (o["emp"] != null && decimal.TryParse((string)o["emp"], out _emp))
            {
                predicate = predicate.And<BestAvailableFIP>(x => x.emp == _emp);
            }
            // FIPSCO_STR
            if (!string.IsNullOrWhiteSpace((string)o["FIPSCO_STR"]))
            {
                string _myStringValue = (string)o["FIPSCO_STR"];
                predicate = predicate.And<BestAvailableFIP>(x => x.FIPSCO_STR.Contains(_myStringValue));
            }
            // FIPSCODE
            double _FIPSCODE;
            if (o["FIPSCODE"] != null && double.TryParse((string)o["FIPSCODE"], out _FIPSCODE))
            {
                predicate = predicate.And<BestAvailableFIP>(x => x.FIPSCODE == _FIPSCODE);
            }
            // FROMDESC
            if (!string.IsNullOrWhiteSpace((string)o["FROMDESC"]))
            {
                string _myStringValue = (string)o["FROMDESC"];
                predicate = predicate.And<BestAvailableFIP>(x => x.FROMDESC.Contains(_myStringValue));
            }
            // LANEMI
            decimal _LANEMI;
            if (o["LANEMI"] != null && decimal.TryParse((string)o["LANEMI"], out _LANEMI))
            {
                predicate = predicate.And<BestAvailableFIP>(x => x.LANEMI == _LANEMI);
            }
            // MPO_ABBV
            if (!string.IsNullOrWhiteSpace((string)o["MPO_ABBV"]))
            {
                string _myStringValue = (string)o["MPO_ABBV"];
                predicate = predicate.And<BestAvailableFIP>(x => x.MPO_ABBV.Contains(_myStringValue));
            }
            // owner
            if (!string.IsNullOrWhiteSpace((string)o["owner"]))
            {
                string _myStringValue = (string)o["owner"];
                predicate = predicate.And<BestAvailableFIP>(x => x.owner.Contains(_myStringValue));
            }
            // PASER
            decimal _PASER;
            if (o["PASER"] != null && decimal.TryParse((string)o["PASER"], out _PASER))
            {
                predicate = predicate.And<BestAvailableFIP>(x => x.PASER == _PASER);
            }
            // PASER_GROUP
            if (!string.IsNullOrWhiteSpace((string)o["PASER_GROUP"]))
            {
                string _myStringValue = (string)o["PASER_GROUP"];
                predicate = predicate.And<BestAvailableFIP>(x => x.PASER_GROUP.Contains(_myStringValue));
            }
            // pr
            decimal _pr;
            if (o["pr"] != null && decimal.TryParse((string)o["pr"], out _pr))
            {
                predicate = predicate.And<BestAvailableFIP>(x => x.pr == _pr);
            }
            // RDNAME
            if (!string.IsNullOrWhiteSpace((string)o["RDNAME"]))
            {
                string _myStringValue = (string)o["RDNAME"];
                predicate = predicate.And<BestAvailableFIP>(x => x.RDNAME.Contains(_myStringValue));
            }
            // SPDR_ABBV
            if (!string.IsNullOrWhiteSpace((string)o["SPDR_ABBV"]))
            {
                string _myStringValue = (string)o["SPDR_ABBV"];
                predicate = predicate.And<BestAvailableFIP>(x => x.SPDR_ABBV.Contains(_myStringValue));
            }
            // TODESC
            if (!string.IsNullOrWhiteSpace((string)o["TODESC"]))
            {
                string _myStringValue = (string)o["TODESC"];
                predicate = predicate.And<BestAvailableFIP>(x => x.TODESC.Contains(_myStringValue));
            }
            // TYPE
            if (!string.IsNullOrWhiteSpace((string)o["TYPE"]))
            {
                string _myStringValue = (string)o["TYPE"];
                predicate = predicate.And<BestAvailableFIP>(x => x.TYPE.Contains(_myStringValue));
            }

            return predicate;
        }

        internal override System.Linq.Expressions.Expression<Func<TEntity, bool>> CreateCriteriaExpressionForCustomProperties<TEntity>(string myCriteria)
        {
            var predicate = PredicateBuilder.True<TEntity>();

            return predicate;
        }
    }
}

The JsonLinqParser base class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace DAL
{
    abstract class JsonLinqParser
    {
        abstract internal Expression<Func<TEntity, bool>> CreateCriteriaExpression<TEntity>(string myCriteria)
            where TEntity : System.Data.Objects.DataClasses.EntityObject;
        abstract internal Expression<Func<TEntity, bool>> CreateCriteriaExpressionForCustomProperties<TEntity>(string myCriteria)
            where TEntity : System.Data.Objects.DataClasses.EntityObject;
    }
}

The factory class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAL
{
    internal static class JsonLinqParserFactory
    {
        internal static JsonLinqParser GetParser(Type type)
        {
            switch (type.Name)
            {
                case "BestAvailableFIP":
                    return new JsonLinqParser_Paser();
                default:
                    //if we reach this point then we failed to find a matching type. Throw 
                    //an exception.
                    throw new Exception("Failed to find a matching JsonLinqParser in JsonLinqParserFactory.GetParser() - Unknown Type: " + type.Name);
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T09:07:32+00:00Added an answer on May 24, 2026 at 9:07 am

    The problem is that JsonLinqParser_Paser‘s signatures are generic, type-agnostic, and your implementation is its specialization for concrete BestAvailableFIP type. This is not a covariance issue, it’s just type incompatibility (at compiler level).

    The solution is to make JsonLinqParser to be generic type (not having generic methods) – or even an interface, then make JsonLinqParser_Paser to implement JsonLinqParser<BestAvailableFIP>. We’ll then have everything matching.

    The IJsonLinqParser interface:

    interface IJsonLinqParser<TEntity>
        where TEntity : System.Data.Objects.DataClasses.EntityObject
    {
        Expression<Func<TEntity, bool>> CreateCriteriaExpression(string myCriteria);
        Expression<Func<TEntity, bool>> CreateCriteriaExpressionForCustomProperties(string myCriteria)
    }
    

    The implementation – signatures for JsonLinqParser_Paser:

    internal class JsonLinqParser_Paser : IJsonLinqParser<BestAvailableFIP>
    {
        public Expression<Func<BestAvailableFIP, bool>> CreateCriteriaExpression(string myCriteria)
        {
            // implementation as yours
        }
    
        public Expression<Func<BestAvailableFIP, bool>> CreateCriteriaExpressionForCustomProperties(string myCriteria)
        {
            // implementation as yours
        }
    }
    

    The factory needs to return IJsonLinqParser<TEntity>, what is not a problem as we know TEntity there:

    internal static class JsonLinqParserFactory
    {
        internal static IJsonLinqParser<TEntity> GetParser<TEntity>()
            where TEntity : System.Data.Objects.DataClasses.EntityObject
        {
            switch (typeof(TEntity).Name)
            {
                case "BestAvailableFIP":
                    return (IJsonLinqParser<TEntity>) new JsonLinqParser_Paser();
                default:
                    //if we reach this point then we failed to find a matching type. Throw 
                    //an exception.
                    throw new Exception("Failed to find a matching JsonLinqParser in JsonLinqParserFactory.GetParser() - Unknown Type: " + typeof(TEntity).Name);
            }
        }
    }
    

    And finally in GetByCriteria you can have:

    IJsonLinqParser<TEntity> parser = JsonLinqParserFactory.GetParser<TEntity>();
    

    No need for <TEntity> in parser method calls now, as parser is already TEntity-specific.

    Hope this helps.

    By the way, your factory infrastructure can be easily replaced by good IoC tool.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a function called FindSpecificRowValue that takes in a datatable and returns the
I have a function called Colorbox (jQuery plugin) that takes a number of parameters
I have a function called test in namespace buzz . From this test function
I have a function called: void initializeJSP(string Experiment) And in my MyJSP.h file I
I have a function that I use called sqlf(), it emulates prepared statements. For
I have a user defined function in SQL called getBuisnessDays it takes @startdate and
I have a javascript function that manipulates the DOM when it is called (adds
I have some jQuery code. I have called an Ajax function file, file.php, that
i have a function called ViewComments() which retrieve contents from database using SQL commands
I have a function called ApiCalls() that is wrapped in a locker because the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.