[英]EF Core strange behaviour
I'm using EF Core 3.0 code first.我首先使用 EF Core 3.0 代码。 I have this loop:
我有这个循环:
foreach (var profileCount in quantity)
{
//here I get the exception:
var oldItem = dc.Stock.Items.FirstOrDefault(a => a.Profile.Id == profileCount.Key);
if (oldItem == null)
{
dc.Stock.Items.Add(new Item
{
Price = 0,
ProfileId = profileCount.Key,
Quantity = profileCount.Value,
WasChanged = false
});
}
}
Stock.Items
is empty(not null). Stock.Items
为空(不为空)。 First iteration works fine, on the second one I get第一次迭代工作正常,第二次我得到
System.NullReferenceException: Object reference not set to an instance of an object.
System.NullReferenceException:未将对象引用设置为对象的实例。
I guess it's because I add and try to read from the same collection, but I'm not sure why exactly this is happening.我想这是因为我添加并尝试从同一个集合中读取,但我不确定为什么会发生这种情况。
When you insert your first item ( dc.Stock.Items.Add(new Item
) you don't add a Profile
, so on the next iteration a.Profile.Id
will be a NullReferenceException
.当您插入第一个项目 (
dc.Stock.Items.Add(new Item
) 时,您不会添加Profile
,因此在下一次迭代中a.Profile.Id
将是NullReferenceException
。
Either assign a Profile
when you add a new item, or check for null in your FirstOrDefault
.在添加新项目时分配
Profile
文件,或者在FirstOrDefault
检查 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.