question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to use "dynamic queries" with Dynamic columns #964 feature?

See original GitHub issue

Hi, it seems that

var filteringColumn = "FirstName";
var sortingColumn = "LastName";
var filter = "John";

db.GetTable<Person>()
    .Where(p => Sql.Property<object>(p, filteringColumn) == filter)
    .OrderBy(p => Sql.Property<object>(p, sortingColumn))
    .ToList();

from current #964 feature implementation is actualy not “fully implemented”. “Only constant strings are alowed for member name in Sql.Property expressions.”. Will this be implemented in the future.

I have entity

[Table("PRODUCT")]
public partial class Product
{
...
 public double PRICE1 { get; set; }
 public double PRICE2 { get; set; }
 public double PRICE3 { get; set; }
 public double PRICE4 { get; set; }
 public double PRICE5 { get; set; }
...
}

//I want to query with

string whichPriceName = "PRICE" + settings.PriceID.ToString();

from p in dbContext.Db.GetTable<Product>()
                       select new ProductDTO
                       {
                           ID = p.ID,
                           PRICE = Sql.Property<double>(p, whichPriceName )
                       };

//Possible (current) solution to my problem is using expression method in Product Entity

 [ExpressionMethod("WhichPriceExpression")]
        public double WhichPrice(int priceID)
        {
            //local
            switch (priceID)
            {
                case 5:
                    return PRICE5;
                case 4:
                    return PRICE4;
                case 3:
                    return PRICE3;
                case 2:
                    return PRICE2;
                default:
                    return PRICE1;
            }

        }

        public static Expression<Func<Product, int, double>> WhichPriceExpression()
        {
            return (product, index) => index == 5 ?
            product.PRICE5: index == 4 ?
            product.PRICE4: index == 3 ?
            product.PRICE3: index == 2 ?
            product.PRICE2: product.PRICE1;
        }

          from p in dbContext.Db.GetTable<Product>()
                       select new ProductDTO
                       {
                           ID = p.ID,
                           PRICE = p.WhichPrice(settings.PriceID)
                       };

The expression method is actually translated to SQL CASE statement which is not nice, if there are a lot of PRICE{X} fields…

Is technically possible in Linq2DB to have expression method with parameter…


 public static Expression<Func<Product, double>> WhichPriceExpression(int priceID)
        {
            switch (priceID)
            {
                case 5:
                    return (product) => product.PRICE5;
                case 4:
                    return (product) => product.PRICE4;
                case 3:
                    return (product) => product.PRICE3;
                case 2:
                    return (product) => product.PRICE2;
                default:
                    return (product) => product.PRICE1;
            }
        }

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
sdanylivcommented, Apr 10, 2018

Unfortunately yo can not use this feature in that way. I will extend it. But for your case i have created working solution using Sql.Extension:

public static class MySql
{
	class WithPriceBuilder : Sql.IExtensionCallBuilder
	{
		public void Build(Sql.ISqExtensionBuilder builder)
		{
			var index = builder.GetValue<int>(1);
			var field = builder.GetExpression(0) as SqlField;
			if (field == null)
				throw new Exception("Entity required as parameter");

			var fieldName = "PRICE" + index;
			var table = (SqlTable)field.Table;
			if (!table.Fields.TryGetValue(fieldName, out var newField))
			{
				newField = new SqlField();
				newField.Name = fieldName;
				newField.Table = table;
				table.Fields.Add(fieldName, newField);
			}

			builder.ResultExpression = newField;
		}
	}

	[Sql.Extension("", BuilderType = typeof(WithPriceBuilder), ServerSideOnly = true)]
	public static double WithPrice<T>(T entity, [SqlQueryDependent] int index)
	{
		throw new NotImplementedException();
	}
}

usage

var whichPriceName = 1;
var query = from p in db.GetTable<Product>()
	select new ProductDTO
	{
		ID = p.PriceID,
		PRICE = MySql.WithPrice(p, whichPriceName)
	};

Not so trivial but before i fix Dynamic Columns it’s only one way. As you can see this method can be easily adopted to accept any column names.

0reactions
MaceWinducommented, Apr 27, 2018

should be fixed by #1102

Read more comments on GitHub >

github_iconTop Results From Across the Web

why I need a dynamic query for "column value from a query"
You need "dynamic SQL" because SQL will NOT allow you to use a parameter as a column name or a table name. You...
Read more >
Dynamic Column Selection in Power Query
How to select columns based on a condition in Power Query. ... Query for a while, you'd be familiar with the Remove Other...
Read more >
Building Dynamic Table-Driven Queries
One technique I use for minimizing maintenance is making my queries dynamic. Dynamic queries, while not right for every situation, ...
Read more >
Dynamic Columns - MariaDB Knowledge Base
Dynamic columns allow one to store different sets of columns for each row in a table. It works by storing a set of...
Read more >
Dynamic Column Names in Power Query - YouTube
Learn how to create dynamic column names in Power Query using a mix of Table.RenameColumns() and Table.ToColumns() function.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found