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?