可为null的对象必须有一个值,Linq到SQL,MVC问题
本文关键字:Linq SQL 问题 MVC 有一个 null 对象 可为 | 更新日期: 2023-09-27 18:29:16
我为一位已经离开公司并且对MVC不太熟悉的开发人员接管了一个项目。当运行程序时,我得到了一个错误,"Nullable对象必须有一个值"。
表中的一个单元格由以下内容填充:
<td>@SRA_Acquire.Models.Auth.Users.GetUserNameById((int)issue.UserID)</td>
由以下内容填充:
public static string GetUserNameById(int userId)
{
return GetUserById(userId).Name;
}
internal static UserProfile GetUserById(int userId)
{
var db = new UsersContext();
return db.UserProfiles.Where(c => c.UserId == userId).Single();
}
当遍历代码时,userId是正确的,但我收到错误,指出c.UserID does not exist in the current context
然而,在我的AccountModels.cs
中,它显示
public class UsersContext : DbContext
{
public UsersContext()
: base("AuthContext")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<UsersInRoles> UsersInRoles { get; set; }
public DbSet<Roles> Roles { get; set; }
}
[Table("UserProfile", Schema = "dbo")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public bool IsLockedOut { get; set; }
}
我错过了什么?
尝试更新c.UserId == userId
条件以避免出现这样的错误:
c => c.UserId != null && c.UserId == userId