Giter Site home page Giter Site logo

zzzprojects / system.linq.dynamic.core Goto Github PK

View Code? Open in Web Editor NEW
1.5K 52.0 221.0 40.24 MB

The .NET Standard / .NET Core version from the System Linq Dynamic functionality.

Home Page: https://dynamic-linq.net/

License: Apache License 2.0

C# 20.33% CSS 0.92% JavaScript 0.48% Batchfile 0.01% HTML 78.26% PowerShell 0.01% ASP.NET 0.01%
linq dynamic netstandard core system expression sql entity-framework lamda efcore

system.linq.dynamic.core's Introduction

Library Powered By

This library is powered by Entity Framework Extensions

Entity Framework Extensions

System.Linq.Dynamic.Core

This is a .NET Core / Standard port of the Microsoft assembly for the .Net 4.0 Dynamic language functionality.

Overview

With this library it's possible to write Dynamic LINQ queries (string based) on an IQueryable:

var query = db.Customers
    .Where("City == @0 and Orders.Count >= @1", "London", 10)
    .OrderBy("CompanyName")
    .Select("new(CompanyName as Name, Phone)");

Interpolated strings are supported on .NET 4.6(and above), .NET Core 2.1(and above), .NET Standard 1.3(and above) and UAP 10.0(and above). For example:

string cityName = "London";
int c = 10;
db.Customers.WhereInterpolated($"City == {cityName} and Orders.Count >= {c}");

❗ Breaking changes

v1.3.0

A breaking change is introduced in version 1.3.0 which is related to calling methods on classes. Due to security reasons, it's now only allowed to call methods on the standard predefined classes like (bool, int, string ...). If you want to call a method on an own custom class, annotate that class with the DynamicLinqType. Example:

[DynamicLinqType]
public class MyCustomClass
{
    public int GetAge(int x) => x;
}

If it's not possible to add that attribute, you need to implement a custom CustomTypeProvider and set this to the ParsingConfig and provide that config to the dynamic call.

Useful links

Info

Project  
  Chat Gitter
  Issues GitHub issues
Quality  
  CI Workflow CI Workflow
NuGet  
  System.Linq.Dynamic.Core NuGet
  EntityFramework.DynamicLinq NuGet
  Microsoft.EntityFrameworkCore.DynamicLinq NuGet
  Z.EntityFramework.Classic.DynamicLinq NuGet

Development Details

Frameworks

The following frameworks are supported:

  • net35, net40, net45, net46 and up
  • netstandard1.3, netstandard2.0 and netstandard2.1
  • netcoreapp3.1, net5.0, net6.0, net7.0 and net8.0
  • uap10.0

Fork details

This fork takes the basic library to a new level. Contains XML Documentation and examples on how to use it. Also adds unit testing to help ensure that it works properly.

Some background: I forked from https://github.com/NArnott/System.Linq.Dynamic and added some more functionality there.
My fork is still visible on github [https://github.com/StefH/System.Linq.Dynamic], however I decided to start a new project + nuget to avoid confusion and create the project according to the new VS2017 + .NET Core rules / standards.

However, currently there are multiple nuget packages and projects available:

Project NuGet Author Comment
kahanu/System.Linq.Dynamic System.Linq.Dynamic @kahanu -
kavun/System.Linq.Dynamic.3.5 System.Linq.Dynamic.3.5/ @kavun only 3.5 and VB.NET
NArnott/System.Linq.Dynamic System.Linq.Dynamic.Library @NArnott removed from github + nuget ?
dynamiclinq.codeplex - dialectsoftware -
dynamic-linq - scottgu -

Contribute

The best way to contribute is by spreading the word about the library:

  • Blog it
  • Comment it
  • Star it
  • Share it

A HUGE THANKS for your help.

More Projects

To view all our free and paid projects, visit our website ZZZ Projects.

system.linq.dynamic.core's People

Contributors

alexweav avatar arjenvrh avatar azure-pipelines[bot] avatar cambirch avatar countincognito avatar czielin avatar david-garcia-garcia avatar davidcizek avatar dependabot[bot] avatar glopesdev avatar gregfullman avatar igitur avatar jogibear9988 avatar jonasdaniels avatar jonathanmagnan avatar jotab123 avatar juliengrd avatar lempireqc avatar maschmi avatar nickdarvey avatar nothrow avatar olegnadymov avatar pferraris avatar rockresolve avatar stefh avatar twhidden avatar wertzui avatar yangzhongke avatar yonguelink avatar yyjdelete avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

system.linq.dynamic.core's Issues

Join with dependent subquery?

Question:
Is it possible to do a dynamic join with a dependent sub-query? I'm trying to do the equivalent of this MySQL SQL statement (would be outer cross apply on SQL Server) where I want to join only to a single value on another table where there may be multiple rows that match by certain filter and order criteria:

SELECT * FROM ABC `A`
LEFT OUTER JOIN CONSIGNMENT_TRACKING `AB`
ON `AB`.`SQL_RFA` = (SELECT `SQL_RFA` FROM CONSIGNMENT_TRACKING `ABA` FORCE INDEX(INDEX_01) WHERE( `ABA`.`TRKJOB$$`= `A`.`TRKJOB$$`) ORDER BY ABA.`MILESTONE$$` LIMIT 1)
GROUP BY A.`TRKREF$$`

I thought something like this might work (different tables to above):

a = a.Join(dyn1, "new ( JobID as f1, \"EVENT1\" as f2 )", "new ( JobID as f1, EventID as f2 )", $"new ( {outer}, Max(inner.SQL_RFA) as e{pass}rfa)");
a = a.Join(dyn1, $"e{pass}rfa", "SQL_RFA", $"new ( {outer}, inner as e{pass})");

But it doesn't like the Max(inner.SQL_RFA)

Microsoft.EntityFrameworkCore.DynamicLinq - ToListAsync()?

EF core 1.0.0 has ToListAsync(). I can see that EntityFrameworkDynamicQueryableExtensions class doesn't have this. Will there be a support on this in the future?

using (var context = new TestContext(_optionsBuilder.Options)) { var queryFirstNameContainsTest = context.Persons.Where(x => x.FirstName.Contains("test")); var test = await queryFirstNameContainsTest.Select("new (FirstName,LastName)").Cast<Person>().ToListAsync(); }

received this error

Test Name: WTW.TMS.Compensation.BasePay.Business.Tests.DynamicEFTests.DynamicEFSelectTest
Test FullName: WTW.TMS.Compensation.BasePay.Business.Tests.DynamicEFTests.DynamicEFSelectTest
Test Source: C:\Projects\Tests\DynamicEFTests.cs : line 26
Test Outcome: Failed
Test Duration: 0:00:08.22

Result StackTrace:
at System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)
at Remotion.Linq.Clauses.ResultOperators.CastResultOperator.GetOutputDataInfo(IStreamedDataInfo inputInfo)
at System.Linq.Enumerable.Aggregate[TSource,TAccumulate](IEnumerable1 source, TAccumulate seed, Func3 func)
at Remotion.Linq.QueryModel.GetOutputDataInfo()
at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.SingleResultToSequence(QueryModel queryModel, Type type)
at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CreateAsyncQueryExecutor[TResult](QueryModel queryModel)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddAsyncQuery[TResult](Object cacheKey, Func1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1.System.Collections.Generic.IAsyncEnumerable.GetEnumerator()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.d__1291.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Tests.DynamicEFTests.d__2.MoveNext() in C:\Projects\Tests\DynamicEFTests.cs:line 41
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.b__6_0(Object state)
at Xunit.Sdk.AsyncTestSyncContext.<>c__DisplayClass7_0.b__1(Object _)
Result Message: No coercion operator is defined between types '<>f__AnonymousType0`2[System.String,System.String]' and 'Domain.Entities.Employee.Person'.

Support for netcoreapp1.0?

Not getting any errors when adding the package but it doesn't seem like it finds the package.
Using this under "frameworks" in project.json

"netcoreapp1.0": {
  "imports": [
    "dotnet5.6",
    "dnxcore50",
    "portable-net45+win8"
  ]
}

Compatibility with System.Linq.Dynamic.Library

Is this backwards compatible with System.Linq.Dynamic.Library by Nathan Arnott? That lib seems to have disappeared and I am looking for a way to migrate my code. I think I see you started with a fork from there.

Parse Lambda

Hi StefH!
Are there any way to parse lambda expression:

public class myClass
{
   public void Foo() {};
}

var expressionParams = new ParameterExpression[]
        {
            Expression.Parameter(typeof (myClass), "myObj"),
            Expression.Parameter(typeof (CultureInfo), "CultureInfo")
        };

var expression = "myObj.Foo()";
var myClassInstance = new myClass();
var invokersMerge = new List<object>() {myClassInstance};

DynamicExpressionParser.ParseLambda(false, expressionParams, typeof (myClass), expression)
                .DynamicInvoke(invokersMerge.ToArray());
                .Compile();

But I get error:

  • No applicable method 'Foo' exists in type 'myClass'

DynamicExpression accessibility

Hello,

First of all, thank you for all your effort porting this project to .NET Core.

Is there any chance you could make DynamicExpression class public? The reason for that is because I use "ParseLambda" method to generate dynamic filters in an application by using PredicateBuilders.

Many Thanks.

Take() and Skip() lose ElementType

I'm trying to build a query in different steps like:

IQueryable result;

result = db.DBEntity.Where("Property1 > 0");
....
var result2 = result1.Skip(1).Take(10);

I'm using the ElementType property to get all properties and create a table but, while result returns DBEntity as ElementType, result2 returns Object as ElementType.

Would be possible to implement Skip and Take methods that returns IQueryable of TElement?

Thank you!

Configuration:
EntityFramework Core 1.0.1
Linq Dynamic Core 1.0.5.4

.Contains("") operation Exception

I have an error when I use in my query Where(Name.Contains("value")) but only when I use MySql, with SqlServer works fine.

Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+ '%'' at line 3

I think the problem is how the sql query is sent to the database:
select * from entity where Name like '%' + 'value' + '%'

The same happens with the StartsWith() and the EndsWith() operations.

Is this a problem with the database provider?

Versions:
MySql: "MySql.Data.EntityFrameworkCore": "7.0.5-IR21"
"MySql.Data": "7.0.5-IR21"
"System.Linq.Dynamic.Core": "1.0.6.5"
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0"

The stacktrace:
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 parameterValues, Boolean openConnection, Boolean closeConnection) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues, Boolean manageConnection)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.<_ShapedQuery>d__31.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__152.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at System.Linq.Dynamic.Core.DynamicEnumerableExtensions.ToDynamicList(IEnumerable source)
at DatesAndRates.Host.Controllers.ProviderController.Filtros(jqGridViewModel jqGridParameters)
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__28.MoveNext()

UWP version

Hello,

Is it possible to make this library compatible with UWP ?

Thanks,
Adrien.

Group by multiple columns?

Hi!

I'm working on group by queries on sqlserver. I'm trying to create groups with multiple columns dynamically and I don't know how I can do it.

Example:

Model

    public class Element
    {
        [Key]
        public int Id { get; set; }
        public double Attribute1 { get; set; }
        public double Attribute2 { get; set; }
    }

Queries

I need this query result:
db.Element.GroupBy(el => new { el.Attribute1, el.Attribute2 })

Dynamically:
db.Element.GroupBy("new(Attribute1, Attribute2)")...?

Is it possible?

Thank you very much!

Dynamic Queries seem to lose "Include()"s

// relevant bits of entities...
class Company {
    public string name { get; set; }
}

class Show {
    public string title { get; set; }
    public Company company { get; set; }
}

"search" is a string, posted from a web page.

// this works ... 
var qTotal = _context.Shows.Include( e => e.company ).Include( ... others ... );
qTotal = qTotal.Where( e => e.title.Contains(search) || e.company.name.Contains(search) );

// this throws null exception
var qTotal = _context.Shows.Include( e => e.company ).Include( ... others ... );
qTotal = qTotal.Where("title.Contains(@0) || company.name.Contains(@0)", search);
System.NullReferenceException: Object reference not set to an instance of an object.
   at lambda_method(Closure , TransparentIdentifier`2 )
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.<SkipIterator>d__30`1.MoveNext()
   at System.Linq.Enumerable.<TakeIterator>d__24`1.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__15`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()

From the VS2015 debug window:

Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory: Information: Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [it].[id], [it].[companyid], [it].[slug], [it].[subtitle], [it].[timestamp], [it].[title], [it.company].[id], [it.company].[addressid], [it.company].[name], [it.company].[slug], [it.company].[timestamp], [p].[id], [p].[addressid], [p].[name], [p].[slug], [p].[timestamp]
FROM [Shows] AS [it]
LEFT JOIN [ProductionCompany] AS [it.company] ON [it].[companyid] = [it.company].[id]
LEFT JOIN [ProductionCompany] AS [p] ON [it].[companyid] = [p].[id]
ORDER BY [it].[companyid], [it].[id]
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory: Information: Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [s].[id], [s].[ownerid], [s].[permission], [s].[role], [s].[timestamp], [s].[userId]
FROM [Staff<Show>] AS [s]
INNER JOIN (
    SELECT DISTINCT [it].[companyid], [it].[id]
    FROM [Shows] AS [it]
    LEFT JOIN [ProductionCompany] AS [it.company] ON [it].[companyid] = [it.company].[id]
) AS [it1] ON [s].[ownerid] = [it1].[id]
ORDER BY [it1].[companyid], [it1].[id]
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory: Information: Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [e].[id], [e].[ProductionCompanyid], [e].[allDayEvent], [e].[description], [e].[duration], [e].[masterRecurid], [e].[notes], [e].[recurState], [e].[showid], [e].[start], [e].[timestamp], [e].[venueid]
FROM [Events] AS [e]
INNER JOIN (
    SELECT DISTINCT [it].[companyid], [it].[id]
    FROM [Shows] AS [it]
    LEFT JOIN [ProductionCompany] AS [it.company] ON [it].[companyid] = [it.company].[id]
) AS [it0] ON [e].[showid] = [it0].[id]
ORDER BY [it0].[companyid], [it0].[id]
Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory: Error: An exception occurred in the database while iterating the results of a query.
System.NullReferenceException: Object reference not set to an instance of an object.
   at lambda_method(Closure , TransparentIdentifier`2 )
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__15`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()

System.NullReferenceException: Object reference not set to an instance of an object.
   at lambda_method(Closure , TransparentIdentifier`2 )
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__15`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
Exception thrown: 'System.NullReferenceException' in Microsoft.EntityFrameworkCore.dll

Issue finding indexer

I'm running into an issue with the .Net Core port of dynamic linq.

I'm trying to sort a list of JObjects and I get this error:

No applicable indexer exists in type 'JObject'.

Here's an example

var rows = new List<JObject>();

var row1 = new JObject();
row1["Column1"] = "B";
row1["Column2"] = 2;
rows.Add(row1);

var row2 = new JObject();
row2["Column1"] = "B";
row2["Column2"] = 1;
rows.Add(row2);

var row3 = new JObject();
row3["Column1"] = "A";
row3["Column2"] = 2;
rows.Add(row3);

var row4 = new JObject();
row4["Column1"] = "A";
row4["Column2"] = 1;
rows.Add(row4);

var list = rows.AsQueryable().OrderBy(@"it[""Column1""]").ToList();

Note this code works with the System.Linq.Dynamic dll on a .Net 4.5.2 project.

I believe this issue resides in the FindIndexer method in the ExpressionParser class.

https://github.com/StefH/System.Linq.Dynamic.Core/blob/master/src/System.Linq.Dynamic.Core/ExpressionParser.cs#L1681-L1707

        int FindIndexer(Type type, Expression[] args, out MethodBase method)
        {
            foreach (Type t in SelfAndBaseTypes(type))
            {
#if !(NETFX_CORE || WINDOWS_APP || DOTNET5_1 || UAP10_0 || NETSTANDARD)
                MemberInfo[] members = t.GetDefaultMembers();
#else
                MemberInfo[] members = new MemberInfo[0];
#endif

If you take away the NETSTANDARD check everything seems to work, although I'm not sure if that would effect anything else. I made that change locally and ran all the unit tests and they all passed. There might be better fix, but I'm not as familiar with the code.

Documentation for expression syntax

Thanks for taking up this project; it fills the niche between compile-time LINQ and expressions built using static methods on System.Linq.Expressions,Expression.

The previous incarnation of this project by https://github.com/NArnott had excellent documentation on the expression syntax used by Dynamic LINQ (including nested query expressions such as Any or Where within the string), which this version seems to be lacking.

Is there any such documentation?

Casting a int to a nullable int will throw an error when using linq to entities"Only parameterless constructors and initializers are supported in LINQ to Entities"

Using an expression in the following format - MyDbSet.Select("new (int?(Id))") will throw an error if the Id property is of type int. This seems to be a bug in the original System.Linq.Dynamic project too.

One work around I have found is you can cast it to int64 first and then a nullable int like so MyDbSet.Select("new (int?(int64(Id)))")

The error only gets thrown once you try to evaluate the expression e.g. calling Count() on the first example

Move to .NET Core RTM

Hi!

.NET Core was released today, however, I notice the netstandard1.3 and other .NET Core-related versions of System.Linq.Dynamic.Core 1.0.4 still depend on the prerelease versions of the .NET Core assemblies (e.g. 4.0.11-rc2-24027).

Would it be possible for you to migrate to the final versions?

Thanks!

Can't install using nuget in Asp.Net 4.0 Web Pages project

Thanks for keeping this project alive.

I'm using visual studio 2010, my project is in Asp.Net Web Pages .Net 4.0
When using Nuget 2.8.60318.667 to install the package, Iget the following error:

'System.Linq.Dynamic.Core' already has a dependency defined for 'System.Collections.Concurrent'.

I tried to install the package NetLegacySupport.ConcurrentDictionary 1.1.0 and did it again but got the same error.

Any clues?

Windows 10 uwp support

I would like to use this nice library in a Windows 10 uwp app. I was not able to compile the class DynamicClassFactory. It seems that the framework uap10.0 lacks support for the classes in System.Reflection.Emit like ModuleBuilder, TypeBuilder to create types at run-time. Any thought on this ? Thank you.

Question: External Methods call

Hi StefH!
Are there any way to call an external method like:

public static void Method1(dynamic obj)
{
    //Do something...
}

thisQuery.Select("Method1(it)");

I also tried with a delegate as parameter and doesn't work.

UnitTest : GroupByAndSelect_TestDynamicSelectMember fails

System.Linq.Dynamic.Core.Tests.ComplexTests.GroupByAndSelect_TestDynamicSelectMember [FAIL]
      Assert.Equal() Failure
      Expected: 50
      Actual:   51
      Stack Trace:
           at TestToolsToXunitProxy.Assert.AreEqual[T](T expected, T actual)
        C:\Projects\GitHub\System.Linq.Dynamic.Core\test\System.Linq.Dynamic.Core.Tests\ComplexTests.cs(21,0): at System.Linq.Dynamic.Core.Tests.ComplexTests.GroupByAndSelect_TestDynamicSelectMember()

Can I convert int to string type?

I want to do a dynamic field search, so I need to convert all the fields to string for global search, like below:

var expectedResult = _context.Blogs.Select(b => ((string)((int)(b.BlogId))).Contains("key"));
var result = _context.Blogs.AsQueryable().Select("(string((int)BlogId)).Contains(@p)");

but I know that doesn't work, so is there another way I can do ?

Thanks!

Calling ToString on a nullable column throws error

When writing an entity query you can convert a nullable column to a string

myDbContext.Contact.Select(c => c.NullableIntColumn.ToString());

However this code using the dyanamic linq will not work if the column is nullable and throws a ParseException - "Methods on type 'Int32?' are not accessible"

myDbContext.Contact.Select("NullableIntColumn.ToString()");

Update - Seems you can replicate the ToString in LinqToEntity by doing a conversion to its non nullable type first and then calling to string myDbContext.Contact.Select("int(NullableIntColumn).ToString()");

An another project ?

Hi,

Why do an another project instead of pull the modification for the target netcore to the original repository ?

Methods on type are not accessible error

Trying to call a method in Where clause returns an error: "Methods on type 'SampleModel' are not accessible"

If you add a method to your SampleModel test class:

public class SampleModel 
{
     //.....
     public bool TestMethod(SampleModel other)
     {
          return true;
     }
}

This test should fail:

var testUsers = User.GenerateSampleModels(100).AsQueryable();
var testUsers2 = User.GenerateSampleModels(100).ToArray();

var results = testUsers.Where("TestMethod(@0)", testUsers2);

EntityFramework 1.0.1
Linq Dynamic Core 1.0.6.1

[Question] How can I format a datetime (nullable) field value in select?

I want to format a nullable datetime value, how can I do that?

For example in Linq:

var expected1 = _context.Blogs.Select(x =>
    (string)((DateTime)(x.ModifyDate ?? x.ModifyDate.Value)).ToString("yyyy-MM-dd")).ToArray();

and I tried in dynamic Linq:

var test1 = _context.Blogs.Select<string>(
    "(string)((datetime)(ModifyDate ?? ModifyDate.Value)).ToString(\"yyyy-MM-dd\")").ToArray();

but I got the below error:

System.NotSupportedException : LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

any ideas?

thanks!!

NotEqual filter not working with DateTime

public class Program
{
    public static void Main(string[] args)
    {
        IQueryable<Model> models = new[] { new Model() }.AsQueryable();

        Console.WriteLine(models.Where("Date != null").ToArray().Length);
    }
}

public class Model
{
    public DateTime Date { get; set; }
}

Throws The binary operator NotEqual is not defined for the types 'System.DateTime' and 'System.String'. This works in System.Linq.Dynamic and System.Linq.

Add an overload to the "ToDynamicList" method which accepts a Type

Hello @StefH,

Is it possible to add a new overload to the existing "ToDynamicList" extension method which accepts an instance of a Type class in order to return a typed list?

This may also come as an enhancement to the library itself since most people use it for dynamic operations which they may only know the type of their data at runtime.

As a workaround for now I did the following which is a bit nasty but it is working:

var genericTypeArgument = resultProperty.GetType().GetTypeInfo().GenericTypeArguments[0];

var method = typeof(DynamicEnumerableExtensions).GetMethods().Where(x => x.Name == "ToDynamicList" && x.IsGenericMethod == true).First();

var dynamicQueriedResult = resultProperty.Where(filters);

resultProperty = method.MakeGenericMethod(genericTypeArgument).Invoke(dynamicQueriedResult, new object[] { dynamicQueriedResult});

Many Thanks!

Package 1.0.6.3 install fails for UWP App

In a new blank UWP App with Microsoft.NETCore.UniversalWindowsPlatform 5.1.0, I got a lot of downgrade warnings and this error:
System.Reflection.Emit.ILGeneration 4.0.1 provides a compile-time reference assembly for System.Reflection.Emit.ILGeneration on UAP,Version=v10.0, but there is no
run-time assembly compatible with win10-x86-aot.

When I bump the version to Microsoft.NETCore.UniversalWindowsPlatform 5.2.0, the downgrade warnings are gone but still the same error.

Cannot work with property which in base class.

_dbContext.Users.AsNoTracking().OrderBy("Id").ToListAsync()

throw exception:
No property or field 'Id' exists in type 'ApplicationUser' (at index 0)

But it's going well with System.Linq.Dynamic.Library (without netcore)

If I override the property Id in ApplicationUser, It will be ok.

(Asp.Net Core RC2,ApplicationUser based on IdentityUser)
"System.Linq.Dynamic.Core": "1.0.3"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.