[英]Null AspNetUser using Entity Framework and Code First
I'm learning ASP.NET MVC 5 and I'm having trouble with Entity Framework. 我正在学习ASP.NET MVC 5,但在使用实体框架时遇到了麻烦。 I'm doing code first with an existing database and I made some updates to my database structure so that my other tables use the ID in the
AspNetUser
table as the user ID. 我首先使用现有数据库进行代码,并对数据库结构进行了一些更新,以便我的其他表使用
AspNetUser
表中的ID作为用户ID。 I think I've updated my database properly since it now shows up in Intellisense (I was previously using a custom user table), but for some reason I get a NullReferenceException
when I run the following: 我认为我已经正确更新了数据库,因为它现在显示在Intellisense中(我以前使用的是自定义用户表),但是由于某些原因,在运行以下命令时会收到
NullReferenceException
:
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
MarkContext x = new MarkContext();
var y = x.courses.FirstOrDefault();
foreach(var c in x.courses)
{
System.Diagnostics.Debug.WriteLine(c.courseCode + " " + c.courseTitle + " " + c.AspNetUser.Id);
}
return View();
}
The null
is found on the c.AspNetUser
part of the query. 在查询的
c.AspNetUser
部分上找到null
。 Why would it be null if I've verified that the IDs are properly created? 如果我已验证ID是否已正确创建,为什么它为null? Is it possible that I need to use eager loading for this and, if so, how can I do that in this case?
是否可能需要为此使用急切加载,如果是,在这种情况下该如何做?
Side Note: This is on the About() page that comes with a default MVC setup, so I haven't customized anything really besides this one method in the HomeController
and the database itself. 旁注:这在默认MVC设置随附的About()页面上,因此除了
HomeController
和数据库本身中的一种方法外,我还没有自定义任何内容。
The problem ended up being that, somehow, there was a big block of trailing space inserted in the field that I was linking on in one of the tables. 问题最终是,由于某种原因,我在其中一张表中链接的字段中插入了很大的尾随空间。 While SQL Server didn't acknowledge these spaces, this obviously caused problems with Entity Framework linking them.
尽管SQL Server不承认这些空间,但这显然导致了Entity Framework链接它们的问题。 Removing the trailing spaces from the entries in that column with a simple
RTRIM()
fixed the issue. 使用简单的
RTRIM()
从该列的条目中删除尾随空格RTRIM()
此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.