简体   繁体   English

C#不能将'&'等于实体框架数据

[英]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... 我想从数据库中获取某个值(CD&V),方法是将数据库中的名称与linq语句进行比较,但是我又得到了一个空值...

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. 据我所知,您的代码返回null的唯一方法是匹配对象上的partijID是否为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. PS捕获异常然后完全忽略它绝不是一个好主意。

How is your table designed? 您的桌子如何设计? Does the naam field have a unique constraint on it? naam字段对它有唯一的约束吗? Are you 100% sure you have exactly one row with a value of "CD&V" in the naam field? 您是否100%确定naam字段中的行正好是“ CD&V”值? My guess would be you're getting multiple rows back and then swallow the exception, so partij stays null. 我的猜测是您要返回多行,然后吞下异常,因此partij保持为空。

What's the exception message exactly? 异常消息到底是什么?

Is partijID actually null in the database? 数据库中的partijID实际上为空吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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