我试图将数据添加到数据库错误"对象引用未设置为对象的实例。"

时间:2014-07-03 12:27:18

标签: c# asp.net-mvc repository-pattern unit-of-work

我有2个模型,我将数据传递给

第一

public class MessageRecipient : IDataObject
{
    public int Id { get; set; }
    public string ProviderMessageId { get; set; }
    public string MobileNumber { get; set; }
    public MessageStatus Status { get; set; }

    [ForeignKey("Message")]
    public int MessageId { get; set; }
    public SentMessage Message { get; set; }
}

public enum MessageStatus
{
    Pending, Sent, Delivered, Failed, Unknown

}

第二次

public class SentMessage : IDataObject
{
    public int Id { get; set; }
    public string Message { get; set; }
    public string SenderId { get; set; }
    public DateTime SendDate { get; set; }
    public int RecipientCount { get; set; }
    public int PageCount { get; set; }
    public double CreditsUsed { get; set; }

    [ForeignKey("DeliveryProvider")]
    public int? ProviderId { get; set; }
    public Provider DeliveryProvider { get; set; }

    // User Account Reference (Foreign Key)
    [ForeignKey("User")]
    public int UserId { get; set; }
    public UserAccount User { get; set; }

    public virtual ICollection<MessageRecipient> Recipients { get; set; }
}

然后这是负责发送数据的服务

public int SendMessage(int userId, string senderId, string message, IEnumerable<string> recipients)
{
        var user = _unitOfWork.UserAccountRepository.GetById(userId);

        if (user == null)
            return 0;

        var numberOfPages = Math.Ceiling(message.Length / 180.0); //1sms page = 180 characters
        var numberOfCreditsUsed = numberOfPages * recipients.Count(); // 1 page to 1 recipient == 1 Credit

        //Check if the user has enough credits to complete this process
        if (user.Credit < numberOfCreditsUsed)
        {
            //User doesn't have enough credits
            return 0;
        }

        var sentMessage = new SentMessage()
        {
            Message = message,
            SenderId = senderId,
            SendDate = DateTime.Now,
            RecipientCount = recipients.Count(),
            CreditsUsed = (double)numberOfCreditsUsed,
            PageCount = (int)numberOfPages,
            //ScheduleDate = scheduledDate.HasValue ? scheduledDate.Value : DateTime.Now
        };

        //Create a message recipient object for each of the mobile numbers passed 
        foreach (var contactNumber in recipients)
        {
            var recipient = new MessageRecipient()
            {
                MobileNumber = contactNumber,
                Status = MessageStatus.Pending
            };

            sentMessage.Recipients.Add(recipient);
        }

        user.Credit = user.Credit - numberOfCreditsUsed;
        user.SentMessages.Add(sentMessage);
        _unitOfWork.SentMessageRepository.Save();
        _unitOfWork.MessageRecipientRepository.Save();

        return sentMessage.Id;
    }

这是我得到的错误:

  

对象引用未设置为对象的实例。

     

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

     

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

     

来源错误:

     

第128行:sentMessage.Recipients.Add(收件人)
  第129行:_unitOfWork.MessageRecipientRepository.Save()

我需要知道错误的来源,因为从我自己的角度来看,我认为一切都是正确的。

3 个答案:

答案 0 :(得分:2)

您需要在SentMessage类中实例化您的集合对象。为此,请添加如下构造函数:

public class SentMessage : IDataObject
{
    public SentMessage()
    {
        Recipients = new Collection<MessageRecipient>();
    }

    //snip other code

}

答案 1 :(得分:1)

您必须在“添加”

之前初始化变量“收件人”
//initialize the variable "Recipients"
sentMessage.Recipients.Add(recipient);

我希望能帮助你。

答案 2 :(得分:0)

添加收件人的代码行sentMessage.Recipients.Add(收件人)可能存在NULL错误。在调用任何方法之前,需要初始化收件人。