jge*_*man 6 c# linq linq-to-entities entity-framework
我有以下代码:
public static ContactEventValue GetContactEventValue(ContactEventType contactEventType, string programCode, string brandCode)
{
AdvocacyEntities ent = AdvocacyEntities.GetReadOnlyInstance();
ContactEventValue value = ent.ContactEventValues.SingleOrDefault(
x => x.ContactEventTypeID == contactEventType.ContactEventTypeID
&& x.ProgramCode == programCode && x.BrandCode == brandCode);
}
Run Code Online (Sandbox Code Playgroud)
当我用brandCode和programCode的值调用它时,我从数据库中获得了预期的值.当我进行调用但显式设置x.ProgramCode和x.BrandCode为null时,我从数据库中获取预期的默认值:
ContactEventValue value = ent.ContactEventValues.Single(
x => x.ContactEventTypeID == contactEventType.ContactEventTypeID
&& x.ProgramCode == null && x.BrandCode == null);
Run Code Online (Sandbox Code Playgroud)
但是,当我为programCode和brandCode调用null方法时,我从数据库中返回null!
我尝试根据此问题的答案将==更改为.Equals():Nullable可选参数
所以x.BrandCode.Equals(brandCode)取代x.BrandCode == brandCode和x.ProgramCode.Equals(的程序代码)所取代x.ProgramCode ==的程序代码,但仍然没有工作.
我也试过用?? 操作员,仍然没有工作.
这个问题说没有找到解决方案,并且他/她必须使用存储过程:EF 4查询 - 多参数问题 我真的不想去那里.
有任何想法吗?
我不知道你正在使用什么版本的EF,但是null比较是版本5之前的问题.如果你检查实际发出的SQL,你可能会看到IS NULL
查询中没有使用它.
在EF 6中,您将能够设置UseDatabaseNullSemantics
公开的配置选项DbContext
:
public class MyContext : DbContext
{
public MyContext()
{
this.Configuration.UseDatabaseNullSemantics = true;
}
}
Run Code Online (Sandbox Code Playgroud)
对于EF 5,您可以使用UseCSharpNullComparisonBehavior
底层的设置ObjectContext
:
public class MyContext : DbContext
{
public MyContext()
{
var objectContextAdapter = this as IObjectContextAdapter;
objectContextAdapter.
ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,您需要为项目使用.NET Framework 4.5.如果您不希望使用4.5,那么您可以使用" 如何在实体框架中查询空值"中列出的解决方法之一?.
归档时间: |
|
查看次数: |
1545 次 |
最近记录: |