197

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.

Martin Mulder
  • 12,642
  • 3
  • 25
  • 54
danielovich
  • 9,217
  • 7
  • 26
  • 28

20 Answers20

285

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.

Pete
  • 205
  • 2
  • 8
Martin Mulder
  • 12,642
  • 3
  • 25
  • 54
  • 22
    This solved the problem to me, I suspect this is the solution to the OP as well even though the accepted answer is different. – NibblyPig Jun 29 '14 at 09:24
  • 13
    The answer for me was that I hadn't yet initialized the List I was attempting to filter with `.Where()` -- it was still `null`. – Brian Lacy Dec 22 '14 at 18:23
  • 2
    To avoid this kind of null errors you should either try put a default value in the IEnumerable properties or test them with Any() – Fer R Sep 14 '17 at 00:17
  • 1
    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. – ejcortes Feb 12 '20 at 17:01
  • 1
    This is the correct answer and related to the "Value cannot be null" error message. This error has nothing to do with connection string! – gyousefi Jul 17 '20 at 11:43
  • 1
    this was the cause for me as well. I was querying comparing to another previously loaded collection and that collection was missing some includes. – Miguel Hughes Feb 23 '21 at 18:56
  • Just look at the line number of the exception... in my case it should the exact issue spot. – Andrew Mar 02 '22 at 15:39
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.

anaximander
  • 7,083
  • 3
  • 44
  • 62
  • 3
    In my case it was an incorrect conniption string in code, but still a connection string problem nonetheless. – jleach Mar 15 '16 at 13:04
  • 2
    "isn't necessarily what you'd expect", you can say that one again – Alan Macdonald Sep 24 '20 at 13:25
  • 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. – Deepak Yadav Jun 28 '21 at 08:08
  • I also restarted the docker img and it works – mercury May 07 '22 at 22:16
25

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

Sum None
  • 2,164
  • 3
  • 27
  • 32
  • 2
    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. – Sunday May 29 '20 at 13:12
  • I just curious, if it's keyless entity, why we need to have `set;` hmm... – Benyamin Limanto Jun 11 '22 at 15:28
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.

Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
Guy Lowe
  • 2,115
  • 1
  • 27
  • 37
6

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!
}
Shadi Alnamrouti
  • 11,796
  • 4
  • 56
  • 54
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.

johnny
  • 2,032
  • 1
  • 25
  • 45
4

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.

Jared G.
  • 99
  • 1
  • 4
4

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)
Daniel de Zwaan
  • 3,064
  • 25
  • 24
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.

Franklin Tarter
  • 1,419
  • 1
  • 9
  • 4
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
SharpC
  • 6,974
  • 4
  • 45
  • 40
Ahmedk
  • 21
  • 1
2

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

KennethDale1
  • 103
  • 2
  • 3
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).

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

Muru Bakthavachalam
  • 1,340
  • 12
  • 8
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.

Kirsten
  • 15,730
  • 41
  • 179
  • 318
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.

Sunil Jatolia
  • 41
  • 1
  • 7
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.

Michael Rivera
  • 193
  • 1
  • 7
  • 1
    I started down this path and in some scenarios it might work, but I ran into this pretty quickly https://stackoverflow.com/questions/41881169/navigation-property-should-be-virtual-not-required-in-ef-core – infocyde Feb 06 '20 at 18:39
1

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

Chamila Maddumage
  • 3,304
  • 2
  • 32
  • 43
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.

RaZzLe
  • 1,984
  • 3
  • 13
  • 24
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.

Franco
  • 51
  • 1
  • 7
-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.