为什么我的viewModel对象返回null?

问题描述 投票:0回答:1

我有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-core entity-framework-core asp.net-core-webapi viewmodel
1个回答
2
投票

你忘了初始化消息和用户类。

        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;

输出:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.