Value cannot be null. Parameter name: source

C#Entity FrameworkLinqNullreferenceexception

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

I had this one a while back, and the answer isn't necessarily what you'd expect. This error message often crops up when your connection string is wrong.

At a guess, you'll need something like this:

<connectionStrings>
    <add name="hublisherEntities" connectionString="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True" />
        </parameters>
    </defaultConnectionFactory>
</entityFramework>

What's happening is that it's looking for a data source in the wrong place; Entity Framework specifies it slightly differently. If you post your connection string and EF config then we can check.

Solution 3 - C#

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...

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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!
}

Solution 7 - C#

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.

Solution 8 - C#

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)

Solution 9 - C#

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

Solution 10 - C#

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

Solution 11 - C#

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.

Solution 12 - C#

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

Solution 13 - C#

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

Solution 14 - C#

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.

Solution 15 - C#

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.

Solution 16 - C#

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.

Solution 17 - C#

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

Solution 18 - C#

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.

Solution 19 - C#

If this error comes up when you are trying to deploy the project, make sure your user account has enough permissions to do it.

Solution 20 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondanielovichView Question on Stackoverflow
Solution 1 - C#Martin MulderView Answer on Stackoverflow
Solution 2 - C#anaximanderView Answer on Stackoverflow
Solution 3 - C#Sum NoneView Answer on Stackoverflow
Solution 4 - C#Guy LoweView Answer on Stackoverflow
Solution 5 - C#johnnyView Answer on Stackoverflow
Solution 6 - C#Shadi NamroutiView Answer on Stackoverflow
Solution 7 - C#Franklin TarterView Answer on Stackoverflow
Solution 8 - C#Daniel de ZwaanView Answer on Stackoverflow
Solution 9 - C#AhmedkView Answer on Stackoverflow
Solution 10 - C#KennethDale1View Answer on Stackoverflow
Solution 11 - C#Jared G.View Answer on Stackoverflow
Solution 12 - C#cunderpantsView Answer on Stackoverflow
Solution 13 - C#Muru BakthavachalamView Answer on Stackoverflow
Solution 14 - C#KirstenView Answer on Stackoverflow
Solution 15 - C#Sunil JatoliaView Answer on Stackoverflow
Solution 16 - C#Michael RiveraView Answer on Stackoverflow
Solution 17 - C#Chamila MaddumageView Answer on Stackoverflow
Solution 18 - C#RaZzLeView Answer on Stackoverflow
Solution 19 - C#FrancoView Answer on Stackoverflow
Solution 20 - C#Jarin FarhadView Answer on Stackoverflow