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?