首页 > 解决方案 > 为什么我的 viewModel 对象返回 null?

问题描述

我有 2 个类,Message 和 User,并且我创建了一个包含这两个类的 viewModel:

public class User
{
    [Key]
    public int UserId { get; set; }

    public string Username { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public ICollection<Message>? Messages { get; set; } = new Collection<Message>();

}

public class Message
{
    [Key]
    public int MessageId { get; set; }

    public string MessageContent { get; set; }

    public DateTime DateCreated { get; set; }
}

public class NewMessageViewModel
{
    public Message Message { get; set; }

    public User? Sender { get; set; }

    public User? Receiver { get; set; }
}

但是,当我尝试通过控制器传递 viewModel 并取回一些 json 时,它会出现错误'System.NullReferenceException: 'Object reference not set to an instance of an object.'

我没有正确地通过某些事情,我知道,但对于我的生活,我可以看到什么是错的!我太接近客观性了,所以有人可以指出我犯的愚蠢错误吗?

我的控制器动作:

    [Route("NewMessageViewModel")]
    [HttpGet]
    public NewMessageViewModel GetNewMessageViewModel()
    {

        NewMessageViewModel newmv = new NewMessageViewModel
        {
            Message = { MessageContent = "HelloWord", MessageId = 1, DateCreated = DateTime.Now},
            Receiver = { UserId = 1, Messages = null, FirstName = "Andy", LastName = "Stav", Username = "AndyStav" },
            Sender = { UserId = 2, Messages = null, FirstName = "Test", LastName = "Test", Username = "Test" }

        };

        return newmv;

    }

标签: c#asp.net-coreentity-framework-coreasp.net-core-webapiviewmodel

解决方案


您忘记初始化消息和用户类:

        NewMessageViewModel newmv = new NewMessageViewModel
        {
            Message = new Message { MessageContent = "HelloWord", MessageId = 1, DateCreated = DateTime.Now },
            Receiver = new User { UserId = 1, Messages = null, FirstName = "Andy", LastName = "Stav", Username = "AndyStav" },
            Sender = new User { UserId = 2, Messages = null, FirstName = "Test", LastName = "Test", Username = "Test" }

        };

        return newmv;

输出:在此处输入图像描述


推荐阅读