-2

I'm getting an "Object reference not set to an instance of an object" exception when I'm trying to assign one of the property of my EF object model to a variable but can't figure out why as the EF object definitely contains data and is accessible in the Immediate Window.

I call the following code to get data from a specific organization:

var organizationModelFromDb = this.DbContext.Organizations.
SingleOrDefault(o => o.OrganizationId == 
                organizationEditViewModel.Organization.OrganizationId);

This definitely returns data as I can see data displayed when expanding the tooltip when hovering my mouse over the organizationModelFromDb object. I can also access the data when I type:

organizationModelFromDb.MembershipType

in the Immediate Window but when I try to assign this property from my object model as such:

var membershipType = organizationModelFromDb.MembershipType;

I get the mentioned exception.

Everything within this Controller's method is working as expected but I was in the process of introducing new functionality but I'm stuck with this problem.

Any idea what may be happening. I'm pretty sure I'm assigning EF data to variables using the same technique all over the place in my project but for whatever reason it just won't work in this method.

What am I missing?

UPDATE-1:

This is not a duplicate question. The referenced article deal with the fact that object may actually be null and how best handle each scenario but as explained my object is not actually null. Data is being returned and it is available via the immediate window and the tooltip.

Update-2

This is the data I get when I'm calling "organizationModelFromDb" from the immediate window:

{System.Data.Entity.DynamicProxies.
 OrganizationModel_2AEF19E09C5699B8E172F0AA73D6DB
 71945EF111ADF7AE5EAEB3AD073A15D5A3}

AdditionalDetails:
{System.Data.Entity.DynamicProxies.OrganizationAddition_
05739F8DE2F5D549B3A7FC852AC32ED9C002953ED41AAA7751B12289E23D8A6C}
AutoImport: false
Members: Count = 1
MembershipType: Full
OrganizationId: "4be433d5-48a9-4891-a008-c70fe4cfoie3"
OrganizationName: "My Company"
StatusType: Approved
Website: ""
_entityWrapper: {System.Data.Entity.Core.Objects.Internal.EntityWrapperWithoutRelationships<System.Data.Entity.DynamicProxies.OrganizationModel_2AEF19E09C5699B8E172F0AA73D6DB71945EF111ADF7AE5EAEB3AD073A15D5A3>}

As you can see, there is data in the object.

But as mentioned, when I call this line of code:

var membershipType = organizationModelFromDb.MembershipType;

in my code, I get the exception with the following StackTrace:

"System.NullReferenceException: Object reference not set to an instance of an object.

at Mywebsite.Controllers.OrganizationsController.d__8.MoveNext() in C:\Work\MyWebsite\Controllers\OrganizationsController.cs:line 349"

Hope this helps resolving my problem.

Update-3

I've removed the code originally provided in this update to keep things tidy rather than providing yet another update but the code below is the full code contained in my controller but note that I've removed unnecessary code for readability sake:

var organizationModelFromDb = await this.DbContext.Organizations
    .FirstOrDefaultAsync<OrganizationModel>(o => o.OrganizationId ==
             organizationEditViewModel.Organization.OrganizationId);

if (ReferenceEquals(organizationModelFromDb, null))
    return HttpNotFound();

organizationModelFromDb.StatusType = StatusType.Approved;

var memberModelsFromDb =
    this.DbContext.Members.Where(
        m => m.OrganizationId == 
            organizationEditViewModel.Organization.OrganizationId).ToList();

if (memberModelsFromDb.Count > 0)
{
    foreach (var memberModel in memberModelsFromDb.ToList())
    {
        var user = new ApplicationUser
        {
            UserName = memberModel.Email,
            Email = memberModel.Email,
            UserType = UserType.IsMember
        };

        var password = RandomPassword.Generate();
        var result = await this.UserManager.CreateAsync(user, password);

        if (result.Succeeded)
        {
            await this.UserManager.AddToRoleAsync(user.Id, JoiffRoles.IsMember);

            try
            {
                var membershipType = organizationModelFromDb.MembershipType;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            string code = await this.UserManager.
                            GenerateEmailConfirmationTokenAsync(user.Id);
            string codeHtmlVersion = HttpUtility.UrlEncode(code);

            new Thread(async () =>
            {
                await CustomEmailService.
            SendConfirm(this, Request, user, codeHtmlVersion);
            }).Start();
        }
    }
}

Now as you can see, there's nothing special about this code. I'm checking if an organization exists, then I'm getting all the members for that organization and then I'm looping through each member and creating a user and adding roles to the database. Once created successfully, it sends an email to the newly created user with credential information.

Now the weird part, the exception "Object reference not set to an instance of an object" occurs with the above code but somehow, it doesn't occur if I comment either section of code:

1) Remove everything above the try/catch but leave the email section below the try catch:

var password = RandomPassword.Generate();
var result = await this.UserManager.CreateAsync(user, password);

if (result.Succeeded)
{
   await this.UserManager.AddToRoleAsync(user.Id, JoiffRoles.IsMember);
   …
}

2) Remove the email section

new Thread(async () =>
{
   await CustomEmailService.SendConfirm(this, 
   Request, user, codeHtmlVersion);
}).Start();

I know this sounds ridiculous, I've gone through it over and over again and if I leave the code as is, I get this error when trying to set the variable to the OrganizationFromDb.MembershipType. If I remove either of the section mentioned above, everything works as expected.

As @CamiloTerevinto mentioned, I do believe it is related to something that hasn't been fully fetched and is only partially built but how are either section affecting this?

Any suggestions?

Thierry
  • 6,142
  • 13
  • 66
  • 117
  • @JSteward This is not a duplicate question as the article your referencing is not tackling my issue. My issue is related to EF and the error I'm getting is only occurring when assigning it to a variable at run-time. If I've missed the section in the article you've provided, can you please mention where can I find the "duplication" that I may have missed. Thanks. – Thierry Jul 25 '18 at 00:09
  • @mjwills, interesting. I thought it would have been the specific object model i.e. OrganizationModel but I see that when I call the organizationModelFromDb.GetType().ToString(), it returns System.Data.Entity.DynamicProxies.OrganizationModel_2AEF19E09C5699B8E172F0AA73D6DB71945EF111ADF7AE5EAEB3AD073A15D5A3 – Thierry Jul 25 '18 at 00:18
  • @mjwills I saw that "MoveNext" alright but it shouldn't be throwing this error as organizationModelFromDb should contain a single object based on this: this.DbContext.Organizations.SingleOrDefault… and as you saw in my update, the data displayed in the immediate window does not display any "MoveNext" exception, I'll go ahead and update my question again with as much code as possible but I'm pretty sure I've provided everything that's required. – Thierry Jul 25 '18 at 00:34
  • 2
    The fact that you are seeing classes from the `System.Data.Entity.DynamicProxies.` namespace means that you are working with EF entities partly built/queried. Please add the entire action code – Camilo Terevinto Jul 25 '18 at 00:45
  • @CamiloTerevinto You are correct and I've been looking into this a bit more but still no luck. In the updated code, I changed my code to use the `FirstOrDefaultAsync` instead of `FirstOrDefault` but it made no difference. I also specified the type hoping it would convert my object to the specific model rather than what looks like an anonymous type, but that didn't work either i.e. var organizationModelFromDb = await this.DbContext.Organizations .FirstOrDefaultAsync…. but I do think it is related to this alright. – Thierry Jul 25 '18 at 00:53
  • Shoot, I think I've figured it out! Give me a minute!! I just re-ran my code and commented everything but that line and it worked! This line of code is within a loop where I'm looping through another collection of data also pulled via EF. I have a feeling I'm going to have to use .ToList() on the loop to ensure that the data is fully pulled out of EF rather than partially. Let me confirm. – Thierry Jul 25 '18 at 00:56
  • Damn, error is back even after I called the .ToList() on my loop. Note that I did not include the code for the loop as the section of the code that throws the error is not using the object from this ForEach loop. – Thierry Jul 25 '18 at 01:02
  • @mjwills This is getting more weird by the second. I'm going to update my answer in a second but this just doesn't make sense as now I've got it to work with the loop but I've left code commented out which has nothing to do with my issue. I'm confused!??? – Thierry Jul 25 '18 at 01:04
  • I'm going to have to investigate this some more tomorrow as its nearly 2:30am here but I have found the source of the problem but I don't understand why it is affecting this specific line of code while it hasn't affected anything else before. It has nothing to do with any of the code I've provided!! Makes no sense, well not to me anyway! – Thierry Jul 25 '18 at 01:25
  • @mjwills I've updated my answer. See update-3. I know it doesn't make sense but these are the facts. – Thierry Jul 26 '18 at 01:20
  • @CamiloTerevinto I've updated my answer. See update-3. I know it doesn't make sense but these are the facts. – Thierry Jul 26 '18 at 01:20

1 Answers1

0

I haven't got to the bottom as to why this is happening nor why does it work when removing snippets of codes as mentioned in my updates but I'm pretty sure it is indeed related to what @CamiloTerevinto previously mentioned regarding the EF entity being only partially built/queried.

I can only assume that displaying data in the Immediate window and/or via the tooltip behaves differently than using it at run-time when assigned to a variable.

Anyway, rather than trying to fixed and/or figure out why removing these snippets of codes did the trick, I thought I'd try a different approach.

Since my organization details were only required to be pulled once there was no need for it to be within the members loop, so

I decided to assign the MembershipType variable outside the Members loop

and this appeared to have done the trick.

I wonder if it is related to EF's lazy loading or something similar where it is trying to fetch the organization's EF entity details when requested within a loop that's also fetching details about another object. I'm not sure to be honest.

Would love someone to highlight and explain the actual reason.

I hope this help.

Thierry
  • 6,142
  • 13
  • 66
  • 117