219

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.

4
  • 2
    You might want to look into this question and its answers: stackoverflow.com/questions/3244336/… Commented Apr 29, 2013 at 14:29
  • 2
    Probably one of the entries in collectin has a null value:est.price = collection["price"]; est.size = collection["size"]; Commented Apr 29, 2013 at 14:29
  • 2
    @AshBurlaczenko oh, you think ? My schema looks like every column can be null. Commented Apr 29, 2013 at 14:34
  • 3
    Could you post your connection string? Commented Apr 29, 2013 at 14:37

22 Answers 22

311

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.

Sign up to request clarification or add additional context in comments.

7 Comments

This solved the problem to me, I suspect this is the solution to the OP as well even though the accepted answer is different.
The answer for me was that I hadn't yet initialized the List I was attempting to filter with .Where() -- it was still null.
To avoid this kind of null errors you should either try put a default value in the IEnumerable properties or test them with Any()
This fixed the problem for me. Even though the accepted answer is different, I think the underlying cause is the same: non initialized collection. Maybe OP didn't include a connection string, or placed it on the wrong node.
This is the correct answer and related to the "Value cannot be null" error message. This error has nothing to do with connection string!
|
52

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.

4 Comments

In my case it was an incorrect conniption string in code, but still a connection string problem nonetheless.
"isn't necessarily what you'd expect", you can say that one again
Yes your problem may not be exactly same but it is a connection string problem, In my case : I was not setting the values of some configuration which I was using earlier and commented now in config file but trying to access them in code. Commented both it worked now.
I also restarted the docker img and it works
27

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

2 Comments

I just had this exact problem while trying to use my Assembly with Linqpad. Thanks for this, I could have wasted way more time. .Net Core 3.1/EF Core 3.1 here.
I just curious, if it's keyless entity, why we need to have set; hmm...
14

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.

Comments

7

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

Comments

6

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.

Comments

5

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.

Comments

5

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)

Comments

3

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.

Comments

2

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

Comments

2

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

1 Comment

Schema="dbo" to Schema="dbo" -- what?
1

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

Comments

1

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

Comments

1

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.

Comments

1

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.

Comments

1

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.

1 Comment

I started down this path and in some scenarios it might work, but I ran into this pretty quickly stackoverflow.com/questions/41881169/…
1

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

Comments

1

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.

Comments

1

Deployment of project failed: Value cannot be null. Parameter Name: Source

I got this error on a React & ASP.Net project when trying to run it, everything built but it complained when trying to "deploy". I was able to fix by noticing a .vscode folder was missing, and in it adding a launch.json file, from which I copied from a working solution. Clearly this wasn't part of what got stored in source control.

someProject.client\.vscode\launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "edge",
            "request": "launch",
            "name": "localhost (Edge)",
            "url": "https://localhost:63210",
            "webRoot": "${workspaceFolder}"
        },
        {
            "type": "chrome",
            "request": "launch",
            "name": "localhost (Chrome)",
            "url": "https://localhost:63210",
            "webRoot": "${workspaceFolder}"
        }
    ]
}

Comments

0

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

Comments

0

I had marked some of my entities as internal (since the DbContect is internal) and then got this error "System.ArgumentNullException: Value cannot be null. Parameter name: source".

Make sure you mark your entities public and not internal:

internal class MyDbContext : DbContext
{
    internal MyDbContext(string connString) : base(connString) { }

    //Do not use internal; entities must be public for EF to see them.
    //NOT THIS: internal virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<Customer> Customers { get; set; }
}

Comments

-3

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.

1 Comment

this is a terrible idea

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.