Error performing LINQ query with equals at where closure

2

When you run the query below:

public ActionResult GridViewPartial()
    {
        if (Session["cod_cli"] != null)
        {
            int cod_cli = Convert.ToInt32(Session["cod_cli"]);

            //var model = db.DadosTecnicos;

            var model = (from s in db.DadosTecnicos
                        where s.id_cliente.Equals(cod_cli)
                        select s).ToList();

            return PartialView("~/Views/DadosTecnicos/_GridViewPartial.cshtml", model);
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }

Error is returned:

However, if I replace Equals with == it works.

But why?

    
asked by anonymous 31.07.2017 / 14:02

1 answer

4

If you want to test the equality of some object, you must use the equality operator that is the == that operates on that type. The Equals() method tests the equality of the object according to the hierarchy. He will not always perform what he expects, unless he masters the functioning of language. I've actually answered the difference between them in What's the difference in using the Equals method for the operator ==? . You have an add-on in another answer . Just use the Equals() with arguments that should only operate on the type, even though with parsimony, understanding if this does not will have some side effect.

When you use a LINQ expression that will be converted to something else, such as SQL, the access provider may interpret each of them differently. In case the provider is transforming the C # equality operator into SQL equality operator. When it finds a Eauals() it should transform into what? This method is not necessarily the same as the operator. It may not even work as the expected type since it is virtual, it does not even know if you can transform into equality operator. Maybe you know if it does, but the compiler does not.

The method is never better than the operator unless you have a clear and reasoned justification for it. You should not follow considerations. I've seen the AP accept a response that teaches you to use Equals() . It has a case that works, but it's almost a coincidence.

This is what I have repeated over and over again: running is different from being right. The right always works, what works can only work in that case, with that given, in that situation. Perhaps the biggest mistake programmers make and many never learn is that running is the worst thing that can happen to you because it gives you the feeling of accomplishment even if the opposite is happening. Often the answer that used Equals() worked right there, but taught wrong. There is a lot of accepted response on the site that is wrong. So I relied little on acceptance and more on voting, although this is increasingly flawed as well, in addition to its inherent flaw since it may be biased towards the response that was given earlier.

    
31.07.2017 / 14:23