使用EF的LINQ查询中的奇怪空引用异常

时间:2014-05-16 19:19:24

标签: c# linq entity-framework ef-code-first

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

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

我有以下&#34;助手&#34; class,ParamValueToList方法间歇性地抛出 null-reference异常

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

上述方法抛出错误的具体声明是

List<ContextParamValue> lst = cpvList
                 .Where(pv => d.Contains(new KeyValuePair<string, string>(pv.ContextParam.Name, pv.Value)))
                 .ToList<ContextParamValue>();

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

  • 对于给定的ContextInstance,只存在1个ContextParamValue
  • 示例,ContextParamValue.ContextParam.Name =&#34; ClientId&#34;和ContextParamValue1.Value =&#34; 1&#34;

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

  • 对于给定的ContextInstance,存在两个或更多个ContextParamValues
  • 示例,ContextParamValue1.ContextParam.Name =&#34; ClientId&#34;和ContextParamValue1.Value =&#34; 1&#34;加上ContextParamValue2.ContextParam.Name =&#34; MotivationId&#34;和ContextParamValue2.Value =&#34; 1&#34;。

我可以确认以下有关辅助方法的内容:

  • d不为null,也不包含任何具有空值的keyvaluepairs
  • cpvList不为空,并且在发生错误时不为空。
  • 在所有情况下,ContextParam都不会为父ContextParamValue实体加载(它仅为第一个ContextParamValue实例加载,但对于后续实例仅加载空值)。
  • 数据库中没有空的ContextParam条目...所有ContextParamValues都有一个ContextParam条目。

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

  

应用:2014-05-16T19:00:20 PID [4800]错误   System.NullReferenceException:未将对象引用设置为实例   一个对象。申请:at   DocumentManagement.Helpers.RuntimeHelper&LT;&GT; c__DisplayClass28.b__27(ContextParamValue   pv)在c:\ Users \ xxx \ Dropbox \ xxx \ Active中   Projects \ xxx \ DocumentManagement \ Helpers \ DocsHelper_RT.cs:第229行   应用程序:在System.Linq.Enumerable.WhereArrayIterator1.MoveNext()   应用程序:在System.Collections.Generic.List1..ctor(IEnumerable1   收集)申请:at   System.Linq.Enumerable.ToList [TSource](IEnumerable1 source)   申请:at   DocumentManagement.Helpers.RuntimeHelper.ParamValuesToList(字符串[]   ParamNames,String [] ParamValues)在c:\ Users \ xxx \ Dropbox \ xxx \ Active中   Projects \ xxx \ DocumentManagement \ Helpers \ DocsHelper_RT.cs:第228行   申请:at   DocumentManagement.Helpers.RuntimeHelper.GetContextInstances(字符串[]   ParamNames,String [] ParamValues,Boolean AsNoTracking)in   C:\用户\ XXX \ Dropbox的\ XXX \活动   Projects \ xxx \ DocumentManagement \ Helpers \ DocsHelper_RT.cs:第262行   应用程序:在xxx.Controllers.ClientController.LoadStep2(Int64   ClientId,String Error()在c:\ Users \ xxx \ Dropbox \ xxx \ Active中   Projects \ xxx \ xxx \ Views \ Client \ ClientController.cs:第198行

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:5)

如果pv.ContextParam为null,则代码抛出异常的唯一方法是,因为这是您解除引用可能导致空指针异常的内容的唯一位置。

如果您有没有相应ContextParam记录的ContextParamValues记录,则会发生这种情况,因此ContextParam将为null。由于我们无法查看您的数据模型,因此您必须检查它。

添加这行代码并检查调试器以查看它是否为真:

bool containsNulls = db.ContextParamValues
    .Include(x => x.ContextParam)
    .Any(x => x.ContextParam == null)

编辑(删除所有中间步骤,如果您感兴趣,请查看历史记录):

嗯,这实际上并没有回答这个问题,但它可以解决你的问题。让我们重新编写您的代码,使其更简单,更高效。如果我正确地阅读了你的代码,你所要做的就是返回与所提供的名称/值对相关联的ContextValueParams的ContextInstances,对吗?

为什么不这样做(根据需要添加包含):

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