logo
down
shadow

Linq Expression throws InvalidOperationException


Linq Expression throws InvalidOperationException

By : subhajit sarkar
Date : November 17 2020, 08:25 AM
around this issue I am building an Expression which should represent an Equals comparison of a property and a constant of type Nullable. In other words, compiling the expression should return a lambda similar to x => (x.Id == value), where both Id and value are of type long?. , Just don't use Expression.Block:
code :
    var body = Expression.Equal(
            Expression.Property(xParam, idProperty),
            Expression.Constant(value, typeof(long?)));

    return Expression.Lambda<Func<T, bool>>(body, xParam);
private static Expression<Func<T, bool>> GetNullableIdEqualsQuery<T>(long? value)
{
    var xParam = Expression.Parameter(typeof(T), "x");
    Expression body;
    if (value == null)
    {
        body = Expression.Not(
            Expression.Property(
                Expression.Property(xParam, "Id"),
                "HasValue"));
    }
    else
    {
        body = Expression.Equal(
            Expression.Property(xParam, "Id"),
            Expression.Constant(value, typeof(long?)));
    }
    return Expression.Lambda<Func<T, bool>>(body, xParam);
}


Share : facebook icon twitter icon
Linq Error: InvalidOperationException: Could not translate expression

Linq Error: InvalidOperationException: Could not translate expression


By : Dustin V
Date : March 29 2020, 07:55 AM
will be helpful for those in need Basically what's happening here is that LINQ to SQL is taking your entire query and trying to convert it into something that SQL Server can understand. The problem, though, is that SQL Server has no concept of DateTime.ToShortDateString, so the conversion to SQL fails.
You'll have to change your query so that it just selects SellEndDate (which will get it as a Nullable) and then when you use the results of that query you can do the conversion to string. For example:
code :
var list = (from p in Products
           select p.SellEndDate).ToList();

// calling ToList() above means we have the entire resultset in memory and
// no longer have to pass the query back to SQL Server

var stuff = from p in list select new
{ 
    selldate = p.SellEndDate == null ?
                   string.Empty :
                   p.SellEndDate.Value.ToShortDateString()
};
Expression.Call on Expression.PropertyOrField on Interface IList<T> throws InvalidOperationException

Expression.Call on Expression.PropertyOrField on Interface IList<T> throws InvalidOperationException


By : Mkid
Date : March 29 2020, 07:55 AM
around this issue It behave like that because of how "inheritance" in interfaces works in .net. Imagine that you have interfaces like that:
code :
public interface ITest 
{
    string Property{get;set;}
}


public interface ISubTest : ITest
{

}
typeof(ITest).GetProperty("Property"); // returns property
typeof(ISubTest).GetProperty("Property"); // returns null 
Linq To SQL Any Throws InvalidOperationException: Sequence contains no elements

Linq To SQL Any Throws InvalidOperationException: Sequence contains no elements


By : cy6057
Date : March 29 2020, 07:55 AM
like below fixes the issue The fix for this was to not use a class variable to save the context and instead instantiate the context locally in each method wrapped in a using.
Aggregate Function in LINQ expression throws error. (cannot be translated into a store expression.)

Aggregate Function in LINQ expression throws error. (cannot be translated into a store expression.)


By : T.Kelly
Date : March 29 2020, 07:55 AM
this one helps. You're having an IQueryable that translates to SQL. Your Aggregate is a method that is unknown to SQL, so there is no way to translate it and you get your exception.
A possible way is to call AsEnumerable() before. This will cause the query to execute and get the data from your SQL server, and the remaining actions are executed in memory (and not on your SQL Server).
code :
myQuery.AsEnumerable().Aggregate(...)
System.InvalidOperationException(An exception was thrown while attempting to evaluate a LINQ query parameter expression)

System.InvalidOperationException(An exception was thrown while attempting to evaluate a LINQ query parameter expression)


By : Barabix
Date : March 29 2020, 07:55 AM
I wish this help you I tried to reproduce your problem with the following code and it worked. Make sure that your object AndroidUser is being sent to your method.
code :
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text;
using WebApplicationLab.Models;
using WebApplicationLab.Utils;

namespace WebApplicationLab.Controllers
{

    [Route("api/[controller]")]
    [ApiController]
    public class RegisterController : ControllerBase
    {
       private readonly AppDbContext _context;

       //Inject your DbContext object instead of create a new instance.
       public RegisterController(AppDbContext context)
       {
          _context = context;
       }

       public string Post([FromBody]User value)
       {
           //Make sure that your object `User` is being sent to your method. 
           if(value == null) 
           {   
              return JsonConvert.SerializeObject("Please inform a valid user!");
           }

          if (!IsUserExists(value.UserName))
          {
              var random = new Random();
              var hash = Common.GetRandomHash(random.Next(1, 100));

              var user = new User()
              {
                  UserName = value.UserName,
                  Hash = Convert.ToBase64String(hash),
                  Password = Convert.ToBase64String(Common.HashPassword(Encoding.ASCII.GetBytes(value.Password), hash))
               };

            _context.Users.Add(user);
            _context.SaveChanges();

            return JsonConvert.SerializeObject("Register Successfully");
        }

          return JsonConvert.SerializeObject("User already exists.");
       }

       private bool IsUserExists(string userName)
       {
           return _context.Users.Any(x => x.UserName.Equals(userName));
        }
    }
}
[Table("Users")]
public class User
{     
    [Key]
    public string UserName { get; set; }

    public string Hash { get; set; }

    public string Password { get; set; }
}
Related Posts Related Posts :
  • Estimating Amount Of time For Tasks Running in Parallel
  • Opening, Changing, and Saving Excel Sheets with DGV
  • Remapping of Database from one server to other TFS-2018
  • SQL Server: Dynamically create Column Names from JSON Auto Data
  • Is it possible to Install .net 4.7 version on my machine when .net 4.8 is already installed?
  • Getting server absolute path in .NET core 2.1
  • Regex to find last word (including symbols) on line
  • Adding element to a couchbase database with f# code
  • How to create "NuGet Package Management Project" for .NET Standard?
  • Blazor BaseURI http vs https issue
  • Does X590Certificate.Build use OCSP if ChainPolicy RevocationMode Online is used?
  • Error "NU3034 This package is signed but not by a trusted signer"
  • Blazor .net version compatibility issues
  • How to test async Task method
  • this project doesn't know how to run the profile docker
  • Azure Cloud Storage SDK UploadFromStreamAsync storing 0 bytes
  • What is the Relaese date for Microsoft Orleans which can support service fabric?
  • Make a string persistent in a .NET application
  • How do I configure Cosmos DB .NET 3.0 SDK to serialize with camel case?
  • Service segmentation fault in AWS EC2
  • How to avoid the compilation error with inconsistent accessibility of class and methods?
  • "Does not implement IControllerFactory.CreateController" in Visual Studio 2010
  • Tabs for a ASP.NET website
  • AccountManagement.UserPrincipal.Current takes 5 seconds
  • Will linq to sql work in an asp.net 2.0 web application?
  • .Net Regular Expression to get parenthetical text at end of <p> tags
  • The Project Location is Not Trusted error in Visual Studio
  • how to tell if a photo was taken in landscape or portrait? JPEG .NET metadata orientation
  • Winform and ValidateChildren()
  • Why need to mention "Supported by the .NET Compact Framework" for classes members?
  • Pass MSI parameters to .NET installer class
  • How to print stack trace of StackOverflowException
  • OnPropertyChange as an Alternative to Triggers in Entity Framework
  • "User Friendly" .net compatible Regex/Text matching tools?
  • Non-Ascii characters not supported by .net?
  • Linq SqlMethods.Like fails
  • To check whether the SQL server DB is working properly or not
  • What is the Difference between GC.GetTotalMemory(false) and GC.GetTotalMemory(true)
  • Which version of .NET is available for Xbox 360?
  • Validation (with custom ErrorTemplate) for a DataTemplate
  • is the threadpool shared - .net
  • WPF RichTextBox - Formatting of typed text
  • "ResizeEnd" equivalent for usercontrols
  • How work with common utils project
  • Using image resource in XAML markup?
  • How to use XML namespace prefixes without xmlns="..." everywhere? (.NET)
  • How to write an altered COM Structured Storage file to Disk?
  • Implementing auditing using Autofac if it support method interception?
  • How can a static class be resolved by the Unity Framework?
  • How to flush DNS cache in Windows Mobile programmatically?
  • how to set autoplay=true in google audio player?
  • Edit dialog, with bindings and OK/Cancel in WPF
  • What does MailMessage.IsBodyHtml do?
  • C# Class Library wont register for COM
  • Robust DateTime parser library for .NET
  • MySql BulkCopy/Insert from DataReader
  • How do I allow all users access to one route within a website with integrated auth?
  • Reading from a oracle temp table in a separate procedure than the one it was populted in
  • Recommendations for IPC between parent and child processes in .NET?
  • F# 1.9.9.9 and lapack
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org