3

I ran into this problem where in I get a null reference exception on insert.

I have two object Models UserInfo and UserConfig. On the first trial, UserConfig references a UserInfo instance

public class UserConfigObject : IUserConfig
    {
        BsonRef("userInfo")]
        public IUserInfo UserInfo { get; set; }

        public string AssignedJob { get; set; }

        public string[] QueueItems { get; set; }

    }

public class UserInfoObject : IUserInfo
    {
        [BsonId]
        public int ID { get; set; }

        public string Name { get; set; }
        public string Username { get; set; }

        public string IPAddress { get; set; }
  }

And a method to insert the data into the database

public void AddUser(IUserConfig user)
        {
            var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
            var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");

            uinCollection.Insert(user.UserInfo);
            uconCollection.Insert(user);

        }

This set up works fine but when I try to change the reference to UserInfo references UserConfig

public class UserInfoObject : IUserInfo
    {
        [BsonId]
        public int ID { get; set; }

        public string Name { get; set; }
        public string Username { get; set; }

        public string IPAddress { get; set; }

        [BsonRef("userConfig")]
        public IUserConfig UserConfig { get; set; }
    }


public class UserConfigObject : IUserConfig
    {
        [BsonRef("userInfo")]
        public IUserInfo UserInfo { get; set; }

        [BsonId(true)]
        public int ConfigID { get; set; }

        public string AssignedJob { get; set; }

        public string[] QueueItems { get; set; }

    }

With a method call for

public void AddUser(IUserInfo user)
        {
            var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
            var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");

            uconCollection.Insert(user.UserConfig);
            uinCollection.Insert(user);
        }

It no longer works, it throws an System.NullReferenceException: 'Object reference not set to an instance of an object.' on uinCollection.Insert(user);

Either v3 or v4, it doesn't work with the latter set up

ReiSchneider
  • 185
  • 1
  • 12

1 Answers1

0

Had the same problem but with collections. I've tried to save collection of invitations like so:

using var db = new LiteRepository(_connectionString);
               
var invitations = new List<Invitation>
{
   // populate list
};

db.Insert(invitations);

The problem is that T parameter resolved as IEnumerable<Invitation> not just Invitation, so if you are inserting a collection, set type explicitly.

db.Insert<Invitation>(invitations);
Potato
  • 397
  • 4
  • 16