简体   繁体   中英

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(IEnumerable 1 source, Func 2 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.

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.

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.

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

I was calling Count on an instance of DbSet with a filter of null ie

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.

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.

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

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.

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)

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

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

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](IEnumerable 1 source, Func 2 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).

在 MVC 中,View screen 调用 Controller 或 Repository.cs 中的方法并将返回值分配给 CSHTML 中的任何控件,但该方法实际上并未在 .cs/controller 中实现,然后 CSHTML 将抛出 NULL 参数异常

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.

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.

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.

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.

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

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.

如果在您尝试部署项目时出现此错误,请确保您的用户帐户具有足够的权限来执行此操作。

在数据库中取一行并使该行中的所有列都为空,如“NULL”。现在使用 try catch 或 if else 传递该 NULL 值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM