-1

I learned MongoDB recently and I wanted to try it out in C#. I have managed to make the Update and Delete functions work. I am having issues with the Create function.

So, I have three classes named Program, Repository, User.

In Repository class, I have:

public async Task CreateUser(ConsoleApplication1.Models.User user)
{
    await _collection.InsertOneAsync(user);
}

In Program, I have following code:

ConsoleApplication1.Models.User new_user;   // Declaring Member of User class
string newUserId = Console.ReadLine();      // Taking Input For ID
new_user.id = new ObjectId(newUserId);      // ID
new_user.First_Name = Console.ReadLine();   // First Name
new_user.Last_Name = Console.ReadLine();    // Last Name
new_user.Age = Console.ReadLine();          // Age
new_user.Address = Console.ReadLine();      // Address
r1.CreateUser(new_user);

Since in Repository class, the CreateUser method has only one parameter that is the member of the User class and the way I declared the new_user in Program class, it is not initialized, which is why I am getting error on:

new_user.id = Console.ReadLine();

How do I fix this ?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Isaac
  • 185
  • 1
  • 2
  • 9
  • 1
    [https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Pio May 25 '20 at 08:52
  • Please edit your question title to describe the problem you are facing, not the technologies and concepts you are using. Please also include enough information for us to help you with your question. For example, you say you're getting an error - what error? – ProgrammingLlama May 25 '20 at 08:54

1 Answers1

3

Before using instance members of class you have to create instance of that class:

ConsoleApplication1.Models.User new_user = new ConsoleApplication1.Models.User();

Same for your repository - you have to create instance of repository and assign it to variable r1. Further reading Static vs Instance

And one more hint - you can use using directive to avoid using full type name each time.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459