The “X” property on “Y” could not be set to a 'null' value. You must set this property to a non-null value of type 'Int32'

前端 未结 11 1418
花落未央
花落未央 2020-12-29 21:38

When I run my application and I click a specific button I get the error:

\"The \"X\" property on \"Y\" could not be set to a \'null\' value. You must set thi         


        
11条回答
  •  醉酒成梦
    2020-12-29 21:50

    For future readers.

    I got this error when I had a multiple result stored procedure.

    As seen here:

    http://msdn.microsoft.com/en-us/data/jj691402.aspx

    If you try to access an item in the first-result, after doing a .NextResult, you may get this error.

    From the article:

        var reader = cmd.ExecuteReader();
    
        // Read Blogs from the first result set
        var blogs = ((IObjectContextAdapter)db)
            .ObjectContext
            .Translate(reader, "Blogs", MergeOption.AppendOnly);   
    
    
        foreach (var item in blogs)
        {
            Console.WriteLine(item.Name);
        }        
    
        // Move to second result set and read Posts
        reader.NextResult();
        var posts = ((IObjectContextAdapter)db)
            .ObjectContext
            .Translate(reader, "Posts", MergeOption.AppendOnly);
    
    
        foreach (var item in posts)
        {
            Console.WriteLine(item.Title);
        }
    

    Now, if before the line

    foreach (var item in posts)
    

    you put in this code

    Blog foundBlog = blogs.FirstOrDefault();
    

    I think you can simulate the error.

    Rule of Thumb:

    You still gotta treat this thing like a DataReader (fire-hose).

    For my needs, I had to convert to a List<>.

    So I changed this:

        foreach (var item in blogs)
        {
            Console.WriteLine(item.Name);
        }  
    

    to this:

        List blogsList = blogs.ToList();
        foreach (var item in blogsList )
        {
            Console.WriteLine(item.Name);
        }  
    

    And I was able to navigate the objects without getting the error.

    Here is another way I encountered it.

        private void DoSomething(ObjectResult blogs, ObjectResult posts)
        {
    
        }
    

    And then after this code (in the original sample)

    foreach (var item in posts)
    {
        Console.WriteLine(item.Title);
    }
    

    put in this code:

    DoSomething(blogs,posts);
    

    If I called that routine and started accessing items/properties in the blogs and posts, I would encounter the issue. I understand why, I should have caught it the first time.

提交回复
热议问题