C# 正在尝试使用Linq从my db获取数据,但收到未处理的异常:System.ArgumentNullException:值不能为null
我正在尝试从数据库中检索用户。我可以更新用户为1的位置,但当我尝试检索值时,我得到一个: 未处理的异常:System.ArgumentNullException:值不能为null 这是我的cs文件C# 正在尝试使用Linq从my db获取数据,但收到未处理的异常:System.ArgumentNullException:值不能为null,c#,entity-framework,linq,C#,Entity Framework,Linq,我正在尝试从数据库中检索用户。我可以更新用户为1的位置,但当我尝试检索值时,我得到一个: 未处理的异常:System.ArgumentNullException:值不能为null 这是我的cs文件 using System; using ConsoleApplication.Models; using System.Linq; using System.Collections; namespace ConsoleApplication { public class Program
using System;
using ConsoleApplication.Models;
using System.Linq;
using System.Collections;
namespace ConsoleApplication
{
public class Program
{
public static void Main()
{
using (var db = new YourContext())
{
//perform database interactions
var TableContents = db.Persons;
Person NewPerson = new Person
{
Name = "Name",
Email = "email@example.com",
Password = "HashThisFirst",
Age = 24
};
db.Add(NewPerson);
db.SaveChanges();
Person RetrievedUser = db.Persons.SingleOrDefault(user => user.ID == 1);
RetrievedUser.Name = "Aaron";
db.SaveChanges();
System.Console.WriteLine(RetrievedUser.Name);
RetrievedUser = db.Persons.SingleOrDefault(user => user.ID == 3);
db.Persons.Remove(RetrievedUser);
db.SaveChanges();
Person ReturnedValues = db.Persons.Where(x => x.ID == 1).FirstOrDefault(); //This is the line causing the the run time error
System.Console.WriteLine(ReturnedValues.Name);
}
}
}
}
这是我得到的全部错误
未处理的异常:System.ArgumentNullException:值不能为空
无效的参数名称:实体位于
Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T值,
字符串参数(名称)位于
Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.删除(TEntity)
ConsoleApplication.Program.Main()上的实体)
根据您提供的信息,.Remove正在报告空输入。这意味着retrievedUser为null,因此数据库中没有ID==3的用户。哪一行产生了错误?你有更多的信息吗?什么属性不能为空?@SkylerAustin。我在导致错误的行旁添加了一条注释,并包含了完整的错误。@Aaron,您的DB是否有ID为3的用户?如果不是,则“retrievedUser”为null,导致.Remove出错。因为调用
Remove
的唯一位置是db.Persons.Remove(retrievedUser)
,这意味着RetreivedUser
为空,这意味着db.Persons.SingleOrDefault(user=>user.ID==3)
为空,这意味着数据库中没有id为3的人。@SkylerAustin,谢谢。张贴你的答案,这样我就可以给你信用