Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange syntax in ef

 var items = context.Items.Where(x => x.IsActive=true).ToList();

Why is correct syntax and working query?

like image 206
i545219 Avatar asked Dec 10 '25 00:12

i545219


1 Answers

This is a very subtle bug in the code. The Where Func needs to return a bool to be valid, but you are setting the value, rather than comparing it, so there's nothing to return, yes?

General Explanation

The code compiles because when you assign a value in c#, e.g. x = 1 that expression is evaluated, and therefore returned, as the value which was assigned (1).

People sometimes use this to lazily instantiate a readonly property, e.g.

private Foo myFoo;

public Foo FooInstance
{
    // set myFoo to the existing instance or a new instance
    // and return the result of the "myFoo ?? new Foo()" expression
    get { return myFoo = myFoo ?? new Foo(); }
}

or assign the same value to multiple variables:

// set z to 1
// set y to result of "z = 1"
// set x to result of "y = z = 1"
x = y = z = 1;

Your Scenario

So what you are doing for each entry in the list is set IsActive to true and return that same true from the function. So then you end up with a new List containing all entries, and all of them have been changed to Active.

If you were using a property in the Where which is not a bool, such as an int, you would get a compilation error:

Cannot implicitly convert type 'int' to 'bool'.

See this as an example (https://dotnetfiddle.net/9S9NAV)

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

public class Program
{
    public static void Main()
    {
        var foos = new List<Foo>()
        {
            new Foo(true, 1),
            new Foo(false, 2)
        };

        // works
        var actives = foos.Where(x => x.IsActive=true).ToList();
        // returns 2, not 1!
        Console.WriteLine(actives.Count);

        // compile error
        var ages = foos.Where(x => x.Age = 1).ToList();
    }
}

public class Foo {
    public Foo(bool active, int age)
    {
        this.IsActive = active;
        this.Age = age;
    }

    public bool IsActive { get; set; }
    public int Age { get; set; }
}
like image 103
Rhumborl Avatar answered Dec 12 '25 14:12

Rhumborl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!