提问人:xinthose 提问时间:5/1/2023 最后编辑:Heretic Monkeyxinthose 更新时间:5/6/2023 访问量:74
new List of Class 对象给出 System.NullReferenceException
new List of Class object gives System.NullReferenceException
问:
我正在将我的项目从 ASP.NET 4.8 升级到 ASP.NET Core 6.0。下面的代码适用于 ASP.NET,但为 Core 提供了错误。我不知道为什么。我尝试了许多不同的方法来解决这个问题,但到目前为止还没有运气。
当我尝试导航到其资源时出现错误:。http://localhost/odata/Users
用户服务 .cs
namespace pal_data.Business
{
public class UserService
{
public List<User> GetData()
{
try
{
var lsret = new List<User>(); // ERROR: System.NullReferenceException: Object reference not set to an instance of an object.
using (SqlConnection con = new(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnPort"].ConnectionString))
{
var strSQL = "select a.*, b.RoleName from AppUser a inner join AccessRole b on a.RoleID = b.AccessRoleID";
using (SqlDataAdapter da = new(strSQL, con))
{
var dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
var item = new User
{
UserID = int.Parse(dr["AppUserID"].ToString() ?? ""),
RoleID = int.Parse(dr["RoleID"].ToString() ?? ""),
Role = dr["RoleName"].ToString() ?? "",
UserName = dr["UserName"].ToString() ?? "",
Name = dr["Name"].ToString() ?? "",
Password = dr["Password"].ToString()
};
lsret.Add(item);
}
}
}
return lsret;
}
catch (SqlException ex)
{
// ...
}
catch (Exception e)
{
// ...
}
}
}
}
用户控制器 .cs
namespace pal_data.Controllers
{
[EnableCors]
public class UsersController : ODataController
{
private readonly UserService m_service = new();
[EnableQuery]
public ActionResult<IEnumerable<User>> Get()
{
return Ok(m_service.GetData());
}
}
}
用户 .cs
namespace pal_data.Models
{
public class User
{
public int UserID { get; set; }
public string? FunctionResult { get; set; }
public int ReturnCode { get; set; }
public int RoleID { get; set; }
public string? Role { get; set; }
public string? UserName { get; set; }
public string? Name { get; set; }
public string? Password { get; set; }
}
}
工作用户服务 .cs
- 这将返回没有 null 错误的数据
namespace pal_data.Business
{
public class UserService
{
public List<User> GetData()
{
var lsret = new List<User>
{
new User
{
UserID = 1,
RoleID = 1,
Role = "asdfsdf",
UserName = "sadfsdf",
Name = "sdfasdf",
Password = "asdfsdf",
}
};
return lsret;
}
}
}
答:
0赞
xinthose
5/6/2023
#1
由于代码在 SQL 查询上失败,因此由于某种原因,此行上显示错误。我想吸取了教训。我的 SQL 查询现在已正确编写(不使用 ),并且实体现在正确返回。var lsret = new List<User>();
ConfigurationManager
评论
var lsret = new List<User>();
永远不应该给你.它一定是别的东西(也许是另一个线程?NullReferenceException
catch
null
ToString()
ToString
.?