1

I have a simple 2 tabled database consisting of Users and Groups. Here are the columns of the tables:

Users:

  • UserID
  • UserName
  • GroupID

Groups:

  • GroupID
  • GroupName

And here are the generated classes:

public partial class Group
{
    public Group()
    {
        this.Users = new HashSet<User>();
    }

    public int GroupID { get; set; }
    public string GroupName { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

-

public partial class User
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public Nullable<int> GroupID { get; set; }

    public virtual Group Group { get; set; }
}

I need to make a method which inserts an user into a given group. If the group doesnt exist, it should create it. I am using Entity Framework. Here is some code:

public class Entry
{
    public static void Main()
    {
        using (var dbContext = new UserSystemEntities())
        {
            var user = new User();
            user.UserName = "h4x0r";

            AddUserToGroup(dbContext, "Admins", user);

            Console.WriteLine("User {0} added successfully.", user.UserName);
        }
    }

    public static void AddUserToGroup(UserSystemEntities dbContext, string groupName, User user)
    {
        using (var dbTransaction = dbContext.Database.BeginTransaction())
        {
            var group = dbContext.Groups.FirstOrDefault(x => x.GroupName == groupName);

            try
            {
                if (group == null)
                {
                    var newGroup = new Group();
                    newGroup.GroupName = groupName;

                    dbContext.Groups.Add(newGroup);                     
                }

                dbContext.Groups.FirstOrDefault(x => x.GroupName == group.GroupName).Users.Add(user);
                dbContext.SaveChanges();
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error occured! " + ex.message);
                dbTransaction.Rollback();
            }

            dbTransaction.Commit();
        }
    }
}

There is a problem with adding the user in the group at:

dbContext.Groups.FirstOrDefault(x => x.GroupName == group.GroupName).Users.Add(user);

throwing a Null Reference Exception and I just cant figure out why. Starring at it for about 20 minutes now and still cant find an answer. Why do I miss?

zhulien
  • 447
  • 1
  • 7
  • 17

1 Answers1

3

The problem is that you are trying to get a group from your DB which doesn't exist and attach a user to it.

If you attach new group to the context which you are doing inside an if clause it won't be saved to the DB automatically, that's why when you call FirstOrDefault method, which queries the database, it fails as your record is not there. So when you have a group (either from a DB or newly created) you can just use your group variable and attach a User to it.

You should modify your code to the following:

    var group = dbContext.Groups.FirstOrDefault(x => x.GroupName == groupName);

    try
    {
        if (group == null)
        {
            group  = new Group();
            group.GroupName = groupName;

            dbContext.Groups.Add(group);                     
        }

        group.Users.Add(user);
        dbContext.SaveChanges();
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error occured! " + ex.message);
        dbTransaction.Rollback();
    }

    dbTransaction.Commit();
Vsevolod Goloviznin
  • 11,256
  • 1
  • 39
  • 47