带有EF的LINQ查询中的奇怪的空引用异常 [英] Strange null reference exception in LINQ query with EF

查看:946
本文介绍了带有EF的LINQ查询中的奇怪的空引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下三个相关的实体类:

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);

我有以下Helper类,其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>();

空引用异常是在以下条件下抛出的 NOT

The null reference exception is NOT thrown under the following condition:


  • 对于给定的ContextInstance,只存在1个ContextParamValue

  • 示例,ContextParamValue.ContextParam.Name =ClientId和ContextParamValue1.Value =1

空引用异常>是在以下条件下抛出:

The null reference exception is thrown under the following condition:


  • 对于给定的ContextInstance,更多ContextParamValues

  • 示例,ContextParamValue1.ContextParam.Name =ClientId和ContextParamValue1.Value =1PLUS ContextParamValue2.ContextParam.Name =MotivationId和ContextParamValue2.Value =1 。

我可以确认以下有关帮助方法的问题:


  • d不为空,也不包含任何具有空值的键值

  • cpvList在所有情况下,ContextParam不为父ContextParamValue实体加载ContextParam(它仅为第一个ContextParamValue实例加载,但后续实例仅加载一个空值,因此不为空,并且在发生错误时不为空。

  • 被加载)

  • 数据库中没有空的ContextParam条目...所有ContextParamValues都有一个ContextParam条目。

  • 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.

以下跟踪 stacktrace 信息在运行时生成:

The following trace and stacktrace information is generated during runtime:


应用程序:2014-05-16T19:00:20 PID [4800]错误
System.NullReferenceException:对象引用未设置为对象的实例
。 c:\Users\xxx\Dropbox\xxx\Active
项目中的
DocumentManagement.Helpers.RuntimeHelper。 \xxx\DocumentManagement\Helpers\DocsHelper_RT.cs:行229
应用程序:在System.Linq.Enumerable.WhereArrayIterator1.MoveNext()
应用程序:在System.Collections.Generic.List1。应用程序:
System.Linq.Enumerable.ToList [TSource](IEnumerable1源)
应用程序:
DocumentManagement.Helpers.RuntimeHelper.ParamValuesToList(字符串[]
ParamNames,String [] ParamValues)在c:\Users\xxx\Dropbox\xxx\Active
Projects \xxx\DocumentManagement\Helpers\DocsHelper_RT。 cs:line 228
应用程序:at
DocumentManagement.Helpers.RuntimeHelper.GetContextInstances(String []

中的ParamNames,String [] ParamValues,Boolean AsNoTracking) c:\Users\xxx\Dropbox\xxx\Active
Projects\xxx\DocumentManagement\Helpers\DocsHelper_RT.cs:line 262
应用程序:在xxx.Controllers。 C:\Users\xxx\Dropbox\xxx\Active
中的ClientController.LoadStep2(Int64
ClientId,String Error)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为null,因为这是唯一可以引用可能导致空指针异常的地方。

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.

如果您具有没有相应ContextParam记录的ContextParamValues记录,则会发生这种情况我们ContextParam将为null。因为我们看不到你的数据模型,所以你必须检查它。

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.

添加这一行代码并检查调试器,看看它是否正确: / p>

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?

为什么不只是这样做(添加包括你认为合适):<​​/ p>

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();
}

这篇关于带有EF的LINQ查询中的奇怪的空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆