实体Sql语句中的value不能为空

本文关键字:不能 value Sql 语句 实体 | 更新日期: 2023-09-27 18:06:04

我的News.cs类与Comment.cs有一对多的关系,如下所示

public class News
{
    public int NewsId { get; set; }    
    [Display(Name = "Title")]
    public string Title { get; set; }    
    [Display(Name = "Details")]
    public string Details { get; set; }    
    public DateTime DateCreated { get; set; }    
    public int AppUserId { get; set; }
    [ForeignKey("AppUserId")]
    public virtual AppUser AppUser { get; set; }   
    public ICollection<Comment> Comment { get; set; }   
}
public class Comment
{
    public int CommentId { get; set; }
    public string CommentText { get; set; }
    public DateTime DateCreated { get; set; }
    public int AppUserId  { get; set; }
    public int? NewsId { get; set; }
    [ForeignKey("AppUserId")]
    public virtual AppUser AppUser { get; set; }
    [ForeignKey("NewsId")]
    public virtual News News { get; set; }
}

我有一个控制器动作,我试图获取一个新闻项目旁边的所有评论,所以我设置了两个viewmodel像这样

public class CommentVM
{    
    public string CommentText { get; set; }
    public DateTime DateCreated { get; set; }
    public string Author { get; set; }    
}
public class NewsCommentsVM
{
    [Display(Name = "Title")]
    public string Title { get; set; }
    [Display(Name = "Details")]
    public string Details { get; set; }
    public DateTime DateCreated { get; set; }
    public string Author { get; set; }
    public List<CommentVM> Comments { get; set; }
}

在我的控制器动作中,我有

public ActionResult Details(int? id)
{
    UOW _unit = new UOW();
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    News news = _unit.NewsRepository.GetByID(id);
    if (news == null)
    {
        return HttpNotFound();
    }
    var model = new NewsCommentsVM()
    {
        Title = news.Title,
        Details = news.Details,
        DateCreated = news.DateCreated,
        Author = news.AppUser.FirstName
        Comments = news.Comment.Select(c => new CommentVM()
        {
            CommentText = c.CommentText,
            Author = c.AppUser.Email,
            DateCreated = c.DateCreated
        }).ToList()
    };
    return View(result);
}

问题是调试器显示评论返回Null,而在数据库中有相关的评论到特定的新闻项目,所以我得到错误

Value不能为空。参数:源

我已经能够在另一个项目中使用此代码而没有问题。

实体Sql语句中的value不能为空

我认为问题是因为您需要将Comments集合属性更改为virtual。如果您希望延迟加载相关实体,则需要遵循以下要求:

public class News
{
    //...  
    public  virtual ICollection<Comment> Comment { get; set; }   
}

现在,如果你已经禁用了延迟加载,另一个选项可以在你的查询中使用Include扩展方法,当你需要找到一个特定的新闻:

int id=3;
var specificNews=context.News.Include(n=>n.Comment).FirstOrDefault(n=>n.Id==id);

这样,相关实体将包含在查询结果