C# 值不能为空。参数名称:来源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16281133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Value cannot be null. Parameter name: source
提问by danielovich
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, 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 ... ...
[ArgumentNullException:值不能为空。参数名称:source] System.Linq.Enumerable.Any(IEnumerable
1 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.
我只想向表中添加一个实体。ORM 是 EF。
采纳答案by anaximander
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.
发生的事情是它在错误的地方寻找数据源;实体框架对其的指定略有不同。如果您发布连接字符串和 EF 配置,那么我们可以检查。
回答by Martin Mulder
Somewhere inside the DbContext is a value that is IEnumerableand is queried with Any()(or Where()or Select()or any other LINQ-method), but this value is null.
DbContext 内部的某处是一个值,该值IEnumerable使用Any()(或Where()或Select()或任何其他 LINQ 方法)进行查询,但该值是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 IEnumerableas a parameter which is NULL.
找出您是否在使用 LINQ 方法的地方将查询放在一起(在示例代码之外的某处),或者您是否将 用作IEnumerableNULL 的参数。
回答by johnny
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.
仅供参考,有人可能会发现它很有用。近 2 天我一直在为这个错误追寻我的尾巴,并且总是在思考一些大问题并寻找可能是问题的类,最后我发现它是一个非常愚蠢的问题,它在 mypage.ascx 中的标记 (HTML) 代码中. 问题是我有一个<asp:EntityDataSource>,它有一个包含属性,我在这里列出了一些其他表,错误地有一个表最近已从数据库中删除,我从未注意到它与其他实体一起返回空值。我刚刚从包含列表中删除了愚蠢的表格,我很高兴。希望这可以帮助某人。
回答by cunderpants
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.
这可能和我的情况一样愚蠢,因为 savechanges 出错,因为数据库没有外键,并且关联被添加到 EDM 表中。我在数据库中添加了外键并重新生成了 EDM 以进行修复。
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)
我看到的错误如下:案例 1 -> 使用 DBContext 进行 EDM Message=Value 时不能为空。参数名称:Source at System.Linq.Enumerable.Any[TSource](IEnumerable 1 source, Func2 谓词)
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.
情况 2 -> 将 ObjectContext 用于 EDM 时 Message=Unable to update the EntitySet 'Contact' 因为它有一个 DefiningQuery 并且元素中不存在支持当前操作的元素。
(Just wanted to throw it in there in case it helps someone).
(只是想把它扔在那里,以防它对某人有帮助)。
回答by Muru Bakthavachalam
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
在MVC中,View screen调用Controller或Repository.cs中的方法,并将返回值分配给CSHTML中的任何控件,但该方法实际上没有在.cs/controller中实现,那么CSHTML将抛出NULL参数异常
回答by Guy Lowe
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,即
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:
我发现在此处传递 null 会导致错误,因此如果过滤器为 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.
这为我解决了问题。对于 DbSet 上的任何其他方法,这也可能是一个问题。
回答by Ahmedk
Resolved with the following solution
通过以下解决方案解决
- Right click on the
edmxfile, select Open with, XML editor - Locate the entity in the
edmx:StorageModelselement - Remove the
DefiningQueryentirely - Rename the
store:Schema="dbo"toSchema="dbo"(if exists) - Remove the
store:Nameproperty
- 右键单击
edmx文件,选择打开方式,XML 编辑器 - 在
edmx:StorageModels元素中定位实体 DefiningQuery完全删除- 重命名
store:Schema="dbo"为Schema="dbo"(如果存在) - 删除
store:Name属性
回答by Kirsten Greed
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.
当我删除该属性时,错误停止发生。
回答by Sunil Jatolia
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.
就我而言,在 IIS 上配置 Web 应用程序时出现问题,当触发任何记录上的更新命令时,会生成此错误。
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.
这是 App_Data 上设置为只读的权限问题。右键单击该文件夹,取消选中只读复选框,您就完成了。顺便说一下,出于测试目的,我使用的是 App_Data 文件夹中的 localdb 数据库。
回答by Franklin Tarter
In case anyone else ends up here with my issue with a DB First Entity Framework setup.
万一其他人因我的 DB First Entity Framework 设置问题而在这里结束。
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.
长话短说,我需要重载 Entities 构造函数以接受连接字符串,原因是能够使用 Asp.Net Core 依赖注入容器从 appsettings.json 中提取连接字符串,而不是从 App.config 神奇地获取它调用无参数构造函数时的文件。
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:
我忘了在新的重载中添加初始化我的 DbSet 的调用。所以自动生成的无参数构造函数看起来像这样:
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.
这真的让我陷入了循环,因为我们 Respository 中使用 DbContext 的一些调用工作正常(那些不需要那些初始化的 DBSet 的调用),而其他调用则抛出 OP 中描述的运行时错误。

