在LINQ查询与EF奇怪的空引用异常 [英] Strange null reference exception in LINQ query with EF
问题描述
我有以下三个相关的实体类:
public class ContextInstance
{
public Int64 Id { get; set; }
public virtual List<ContextParamValue> ContextParamValues { get; set; }
}
public class ContextParamValue
{
public Int64 Id { get; set; }
public virtual Int64 ContextParamId { get; set; }
public virtual ContextParam ContextParam { get; set; }
public virtual ContextInstance ContextInstance { get; set; }
public virtual Int64 ContextInstanceId { get; set; }
public string Value { get; set; }
}
public class ContextParam
{
public Int64 Id { get; set; }
[Required]
public string Name { get; set; }
[DefaultValue("")]
public string Description { get; set; }
}
我已经建立了流畅的关系如下:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Entity<ContextInstance>()
.HasMany(ci => ci.ContextParamValues)
.WithRequired(cpv => cpv.ContextInstance)
.HasForeignKey(cpv => cpv.ContextInstanceId)
.WillCascadeOnDelete(true);
我有以下的帮手类中,ParamValueToList方法,它是间歇扔的空引用异常的:
I have the following "Helper" class, the ParamValueToList method of which is intermittently throwing a null-reference exception:
public class RuntimeHelper : IDisposable
{
DocumentDbContext db;
ConfigurationHelper ch;
private RuntimeHelper()
{
}
public RuntimeHelper(DocumentDbContext context)
{
db = context;
ch = new ConfigurationHelper(context);
}
public List<ContextParamValue> ParamValuesToList(string[] ParamNames, string[] ParamValues)
{
Trace.TraceInformation("-- ParamValuesToList invoked --");
if (ParamNames != null && ParamNames.Length != ParamValues.Length)
throw new System.ArgumentException("ParamNames and ParamValues may not differ in length.");
Dictionary<string, string> d = new Dictionary<string, string>();
for (int i = 0; i < ParamNames.Length; i++)
{
string pName = ParamNames[i];
string pValue = ParamValues[i];
d.Add(pName, pValue);
Trace.TraceInformation("ParamValuesToList Key: " + pName + "; Value: " + pValue + ";");
}
Trace.TraceInformation("Value of db:" + db.ContextParamValues.ToString());
var cpvList = db.ContextParamValues
.Include(x => x.ContextParam)
.ToArray<ContextParamValue>();
List<ContextParamValue> lst = cpvList
.Where(pv => d.Contains(new KeyValuePair<string, string>(pv.ContextParam.Name, pv.Value)))
//.Where(pv => true == true)
.ToList<ContextParamValue>();
Trace.TraceInformation("-- ParamValuesToList executed --");
return lst;
}
public List<ContextInstance> GetContextInstances(List<ContextParamValue> ContextParamValues, bool AsNoTracking = false)
{
if (!AsNoTracking)
return db.ContextInstances
.Include(x => x.ContextClass)
.Include(x => x.ContextParamValues.Select(p => p.ContextParam))
.Include(x => x.Documents)
.AsEnumerable<ContextInstance>() // <-- Allows boolean method as part of LINQ query
.Where(ci => IsSubset(ci.ContextParamValues, ContextParamValues))
.ToList<ContextInstance>();
else
return db.ContextInstances
.Include(x => x.ContextClass)
.Include(x => x.ContextParamValues.Select(p => p.ContextParam))
.Include(x => x.Documents)
.AsNoTracking()
.AsEnumerable<ContextInstance>()// <-- Allows boolean method as part of LINQ query
.Where(ci => IsSubset(ci.ContextParamValues, ContextParamValues))
.ToList<ContextInstance>();
}
public List<ContextInstance> GetContextInstances(string[] ParamNames, string[] ParamValues, bool AsNoTracking = false)
{
return GetContextInstances(ParamValuesToList(ParamNames, ParamValues), AsNoTracking);
}
}
这是扔上述方法的具体声明误差
The specific statement from the above method that is throwing the error is
List<ContextParamValue> lst = cpvList
.Where(pv => d.Contains(new KeyValuePair<string, string>(pv.ContextParam.Name, pv.Value)))
.ToList<ContextParamValue>();
的空引用例外的不的在以下条件下抛出
The null reference exception is NOT thrown under the following condition:
- 存在着,对于一个给定ContextInstance,只有1 ContextParamValue
- 示例,ContextParamValue.ContextParam.Name =客户端Id和ContextParamValue1.Value =1
的空引用异常的是在下列条件下引发强>
The null reference exception is thrown under the following condition:
- 存在着,对于给定ContextInstance,二 - 或 - 更ContextParamValues
- 例,ContextParamValue1.ContextParam.Name =客户端Id和ContextParamValue1.Value =1加ContextParamValue2.ContextParam.Name =MotivationId和ContextParamValue2.Value =1
我可以证实有关问题的helper方法如下:
- d为不为空也不包含空值
- cpvList不是null,不为空
- ContextParam不会在所有情况下的父ContextParamValue实体加载(只加载第一个ContextParamValue实例,但随后的情况下仅一个空值加载)。
- 有数据库中没有空ContextParam项...所有ContextParamValues具有一个ContextParam条目。
任何keyvaluepairs时出现错误
- d is not null nor does it contain any keyvaluepairs with null values
- cpvList is not null and not empty when the error occurs.
- ContextParam does not load for parent ContextParamValue entities in all cases (it only loads for the first ContextParamValue instance but for subsequent instances only a null value is loaded).
- There are no null ContextParam entries in database... All ContextParamValues has one ContextParam entry.
的下面的跟踪的和的堆栈跟踪的运行过程中产生的信息:
The following trace and stacktrace information is generated during runtime:
应用:2014-05-16T19:00:20 PID [4800]错误
System.NullReferenceException:对象不设置到对象的实例
。应用:在
DocumentManagement.Helpers.RuntimeHelper<> c__DisplayClass28.b__27(ContextParamValue
PV)在C:\Users\xxx\Dropbox\xxx\Active
类项目\xxx\DocumentManagement\Helpers\DocsHelper_RT.cs:线229
应用:在System.Linq.Enumerable.WhereArrayIterator1.MoveNext()
应用:在System.Collections.Generic.List1。 .ctor(IEnumerable1
集合)应用:在
System.Linq.Enumerable.ToList [TSource](IEnumerable1源)
应用:在
DocumentManagement.Helpers.RuntimeHelper.ParamValuesToList(的String []
ParamNames,字符串[] ParamValues)在C:\Users\xxx\Dropbox\xxx\Active
Projects\xxx\DocumentManagement\Helpers\DocsHelper_RT。 CS:行228
应用:在
C
DocumentManagement.Helpers.RuntimeHelper.GetContextInstances(字符串[]
ParamNames,字符串[] ParamValues,布尔AsNoTracking):\Users\\ \\xxx\Dropbox\xxx\Active
Projects\xxx\DocumentManagement\Helpers\DocsHelper_RT.cs:行262
应用:在xxx.Controllers.ClientController.LoadStep2(Int64的
客户端ID,字符串错误)在C:\Users\xxx\Dropbox\xxx\Active
Projects\xxx\xxx\Views\Client\ClientController.cs:行198
Application: 2014-05-16T19:00:20 PID[4800] Error System.NullReferenceException: Object reference not set to an instance of an object. Application: at DocumentManagement.Helpers.RuntimeHelper.<>c__DisplayClass28.b__27(ContextParamValue pv) in c:\Users\xxx\Dropbox\xxx\Active Projects\xxx\DocumentManagement\Helpers\DocsHelper_RT.cs:line 229 Application: at System.Linq.Enumerable.WhereArrayIterator1.MoveNext() Application: at System.Collections.Generic.List1..ctor(IEnumerable1 collection) Application: at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) Application: at DocumentManagement.Helpers.RuntimeHelper.ParamValuesToList(String[] ParamNames, String[] ParamValues) in c:\Users\xxx\Dropbox\xxx\Active Projects\xxx\DocumentManagement\Helpers\DocsHelper_RT.cs:line 228 Application: at DocumentManagement.Helpers.RuntimeHelper.GetContextInstances(String[] ParamNames, String[] ParamValues, Boolean AsNoTracking) in c:\Users\xxx\Dropbox\xxx\Active Projects\xxx\DocumentManagement\Helpers\DocsHelper_RT.cs:line 262 Application: at xxx.Controllers.ClientController.LoadStep2(Int64 ClientId, String Error) in c:\Users\xxx\Dropbox\xxx\Active Projects\xxx\xxx\Views\Client\ClientController.cs:line 198
推荐答案
这是您的代码会抛出一个例外是,如果pv.ContextParam是空的唯一方法,因为这是唯一的地方,你被提领的东西,可能会导致空指针异常。
The only way that your code would throw an exception would be if pv.ContextParam were null, because that is the only place you are dereferencing something that might cause a null pointer exception.
如果您有ContextParamValues记录没有相应的记录ContextParam这会发生,从而ContextParam将是空。由于我们无法看到你的数据模型,你将不得不以检查
This would happen if you have ContextParamValues records without a corresponding ContextParam record, thus ContextParam would be null. Since we can't see your data model, you will have to check for that.
添加这行代码,并检查调试程序,看它是否是真的:
Add this line of code and check in the debugger to see if it's true:
bool containsNulls = db.ContextParamValues
.Include(x => x.ContextParam)
.Any(x => x.ContextParam == null)
编辑(删除了所有的中间环节,检查历史如果你有兴趣):
EDIT (removed all the middle steps, check history if you're interested):
那么,这实际上并没有回答这个问题,但它会解决你的问题。让我们只重写代码更简单,更高效。如果我看了你的代码的权利,所有你希望做的是恢复已经与所提供的名称/值对相关ContextValueParams的ContextInstances,是否正确?
Well, this doesn't actually answer the question, but it would solve your problem. Let's just rewrite your code to be simpler and more efficient. If I read your code right, all you're looking to do is return the ContextInstances that have associated ContextValueParams with the provided name/value pairs, correct?
为什么不干脆做到这一点(包括添加你认为合适的):
Why not just do this (add includes as you see fit):
public List<ContextInstance> GetContextInstances(
string[] ParamNames, string[] ParamValues, bool AsNoTracking = false)
{
var p = ParamNames.Zip(ParamValues, (a,b) => a+b);
var ctx = db.ContextInstances
.Where(x => p.All(y => x.ContextParamValues
.Select(z => z.ContextParam.Name + z.Value).Contains(y)));
return (AsNoTracking ? ctx.AsNoTracking() : ctx).ToList();
}
这篇关于在LINQ查询与EF奇怪的空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!