[c#] Value cannot be null. Parameter name: source

This is probably the biggest waste of time problem I have spent hours on solving for a long time.

var db = new hublisherEntities();
establishment_brands est = new establishment_brands();

est.brand_id = 1;
est.establishment_id = 1;
est.price = collection["price"];
est.size = collection["size"];

db.establishment_brands.Add(est);
db.SaveChanges();

This gives me an error of

Value cannot be null. Parameter name: source

stacktrace of

[ArgumentNullException: Value cannot be null. Parameter name: source] System.Linq.Enumerable.Any(IEnumerable1 source, Func2 predicate) +4083335 System.Data.Entity.Internal.InternalContext.WrapUpdateException(UpdateException updateException) +87
System.Data.Entity.Internal.InternalContext.SaveChanges() +193
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +33
System.Data.Entity.DbContext.SaveChanges() +20 ... ...

I just want to add an entity to the table. The ORM is EF.

This question is related to c# entity-framework linq nullreferenceexception

The answer is


And, in my case, I mistakenly define my two different columns as identities on DbContext configurations like below,

builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.Id).UseSqlServerIdentityColumn(); //History Id should use identity column in this example

When I correct it like below,

builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.HistoryId).UseSqlServerIdentityColumn();

I have also got rid of this error.


Take a Row in the database and make all the column null in that row like this "NULL".Now pass that NULL value using try catch or if else.


It could be as silly as in my case where savechanges was erroring bcoz the db did not have foreign keys and associations were added to EDM tables. I added foreign keys in the db and regenerated EDM for a fix.

The errors I was seeing are as follows: Case 1 -> when using DBContext for EDM Message=Value cannot be null. Parameter name: source at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)

Case 2 -> when using ObjectContext for EDM Message=Unable to update the EntitySet 'Contact' because it has a DefiningQuery and no element exists in the element to support the current operation.

(Just wanted to throw it in there in case it helps someone).


I got this error when I had an invalid Type for an entity property.

public Type ObjectType {get;set;}

When I removed the property the error stopped occurring.


I had the same issue with XUnit. The problem was with my database connection. Check your connection string is correct or not.


Resolved with the following solution

  1. Right click on the edmx file, select Open with, XML editor
  2. Locate the entity in the edmx:StorageModels element
  3. Remove the DefiningQuery entirely
  4. Rename the store:Schema="dbo" to Schema="dbo" (if exists)
  5. Remove the store:Name property

I just got this exact error in .Net Core 2.2 Entity Framework because I didn't have the set; in my DbContext like so:

public DbSet<Account> Account { get; }

changed to:

public DbSet<Account> Account { get; set;}

However, it didn't show the exception until I tried to use a linq query with Where() and Select() as others had mentioned above.

I was trying to set the DbSet as read only. I'll keep trying...


In MVC, View screen is calling method which is in Controller or Repository.cs and assigning return value to any control in CSHTML but that method is actually not implemented in .cs/controller, then CSHTML will throw the NULL parameter exception


Using the .Count() without checking for null is one strong reason for this error.

THE FIX:

if(someList != null & someList.Count()>0)
{
    //Now, put your hackable code here!
}

This exception will be returned if you attempt to count values in a null collection.

For example the below works when Errors is not null, however if Errors is null then the Value cannot be null. Parameter name: source exception occurs.

if (graphQLResponse.Errors.Count() > 0)

This exception can be avoided by checking for null instead.

if (graphQLResponse.Errors != null)

Somewhere inside the DbContext is a value that is IEnumerable and is queried with Any() (or Where() or Select() or any other LINQ-method), but this value is null.

Find out if you put a query together (somewhere outside your example code) where you are using a LINQ-method, or that you used an IEnumerable as a parameter which is NULL.


In case anyone else ends up here with my issue with a DB First Entity Framework setup.

Long story short, I needed to overload the Entities constructor to accept a connection string, the reason being the ability to use Asp.Net Core dependency injection container pulling the connection string from appsettings.json, rather than magically getting it from the App.config file when calling the parameterless constructor.

I forgot to add the calls to initialize my DbSets in the new overload. So the auto-generated parameter-less constructor looked something like this:

    public MyEntities()
        : base("name=MyEntity")
    {
        Set1 = Set<MyDbSet1>();
        Set2 = Set<MyDbSet2>();
    }

And my new overload looked like this:

    public MyEntities(string connectionString)
        : base(connectionString)
    {
    }

The solution was to add those initializers that the auto-generated code takes care of, a simple missed step:

     public MyEntities(string connectionString)
        : base(connectionString)
    {
        Set1 = Set<MyDbSet1>();
        Set2 = Set<MyDbSet2>();
    }

This really threw me for a loop because some calls in our Respository that used the DbContext worked fine (the ones that didn't need those initialized DBSets), and the others throw the runtime error described in the OP.


My mistake was forgetting to add the .ThenInclude(s => s.SubChildEntities) onto the parent .Include(c => c.SubChildEntities) to the Controller action when attempting to call the SubChildEntities in the Razor view.

var <parent> = await _context.Parent
            .Include(c => c.<ChildEntities>)
            .ThenInclude(s => s.<SubChildEntities>)
            .SingleOrDefaultAsync(m => m.Id == id);

It should be noted that Visual Studio 2017 Community's IntelliSense doesn't pick up the SubChildEntities object in the lambda expression in the .ThenInclude(). It does successfully compile and execute though.


My reason was different to the rest here so I thought I'd post it for anyone else who might have this issue.

I was calling Count on an instance of DbSet with a filter of null i.e.

dbSet.Count(null);

I found that passing null here was causing the error so I now call the parameter-less method if the filter is null:

 if (filter == null)
 {
     return dbSet.Count();
 }
 else
 {
     return dbSet.Count(filter);
 }

This sorted the issue for me. This may be an issue for any other methods on DbSet as well.


Make sure you are injecting the repository into the service's constructor. That solved it for me. ::smacks forehead::


just as an FYI, somebody may find it useful. I was chasing my tail for this error almost 2 days and was always thinking something big and looking for the classes that might be the issue and finally i found it very stupid issue and it was in my mark up (HTML) code in mypage.ascx. the issue was I have a <asp:EntityDataSource> and this has got a include property and I have some other tables listed here and mistakenly a table was there that has been delete from the database recently and I never noticed and it returning null with other entities. I just removed the stupid table from the include list and I am good to go. hope this can help somebody.


I know this is a long way from the year 2013 of the question, but this symptom can show up if you don't have lazy loading enabled when migrating an ASP.NET 5 app to ASP.NET Core, and then trying to upgrade to Entity Framework Core 2.x (from EF 6). Entity Framework Core has moved lazy loading proxy support to a separate package, so you have to install it.

This is particularly true if all you have loaded is an Entity Framework Core Sql Server package (which turns on Entity Framework just fine).

After installing the proxies package, then, as the docs say, invoke .UseLazyLoadingProxies() on the DbContext options builder (in your Startup DI setup section, or wherever you configure your DbContext), and the navigational property that was throwing the above exception will stop throwing it, and will work as Entity Framework 6 used to.


In my case, the problem popped up while configuring the web application on IIS, When the update command on any record was fired this error got generated.

It was a permission issue on App_Data which set to read-only. Right-click the folder, uncheck the Read-only checkbox and you are done. By the way, for testing purpose, I was using the localdb database which was in App_Data folder.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to nullreferenceexception

How to solve Object reference not set to an instance of an object.? Value cannot be null. Parameter name: source Error checking for NULL in VBScript Checking session if empty or not Checking if an object is null in C# What is a NullReferenceException, and how do I fix it? C# elegant way to check if a property's property is null What does "Object reference not set to an instance of an object" mean?