简体   繁体   中英

C# cannot equal '&' with entityframework data

public int getPartijId(string naam)
    {
        Partij partij = null;

        try
        {
            partij = repository.Partij.Single<Partij>(p => p.naam.Equals(naam));
        }
        catch (InvalidOperationException)
        {

        }

        return partij.partijID;
    }

I want to get a certain value (CD&V) out of our database, by comparing the name in the database with a linq statement but I'm getting a null value back...

With the rest of the values, this method works, but I suspect the problem is '&' in the name/string

也许尝试一下您的Partij仓库是否全部为partijen

partij = repository.Partij.First(p => p.naam.Equals(naam));

As far as I can tell, the only way your code can return null is if the partijID on the matched object is null.

Other options are throwing a null reference exception

Partij partij = null;

try
{
    // this may throw an exception because there may be more or less than one item matching your predicate
    partij = repository.Partij.Single<Partij>(p => p.naam.Equals(naam));
}
catch (InvalidOperationException)
{
    // this is hiding that exception
}

// this will throw another null reference exception because the first call didn't actually set the partij variable
return partij.partijID;

PS It's almost never a good idea to catch an exception then completely ignore it.

How is your table designed? Does the naam field have a unique constraint on it? Are you 100% sure you have exactly one row with a value of "CD&V" in the naam field? My guess would be you're getting multiple rows back and then swallow the exception, so partij stays null.

What's the exception message exactly?

Is partijID actually null in the database?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM