简体   繁体   English

EF Core 奇怪的行为

[英]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.

相关问题 C#EF核心QueryableExtensions.FirstOrDefaultAsync奇怪的行为 - C# EF Core QueryableExtensions.FirstOrDefaultAsync strange behaviour 连接字符串EF代码第一个奇怪的行为 - Connection string EF Code first strange behaviour 使用EF + LINQ的奇怪行为:Include(…).Where(…) - Strange behaviour using EF + LINQ: Include(…).Where(…) EF Core 延迟加载器行为与新实体 - EF Core lazy loader behaviour with new entities EF 核心 3.1。 奇怪的 SetValues 行为 - EF Core 3.1. Strange SetValues ​behavior EF6代码优先,多个级联路径和奇怪的FK行为 - EF6 Code First, multiple cascade paths, and strange FK behaviour 将DbSet传递给参数类型为IEnumerable &lt;&gt;的方法时出现奇怪的EF行为 - Strange EF behaviour when passing DbSet to a method with parameter type IEnumerable<> EF Core 模型中的类行为在哪里 - Where does class behaviour reside in EF Core Models 如何在EF Core中添加自定义添加迁移行为? - How to add custom Add-Migration behaviour in EF Core? 是否可以为外键配置EF核心“ ON UPDATE”行为? - Is it possible to configure EF core “ON UPDATE” behaviour for foreign keys?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM