I have a problem with relationships in Entity-framework
Here is my problem :
I have two classes : User and Group
- A group must have ONE Owner (User)
- A group can have 0 or severals Members (User)
- An User can be the owner of 0 or severals group
User.cs :
public class User
{
[Key]
public int userId { get; set; }
[Display(Name="Firstname")]
public string firstname { get; set; }
[Display(Name = "Lastname")]
public string lastname { get; set; }
[Display(Name = "Email")]
public string email { get; set; }
}
Group.cs :
public class Group
{
[Key]
public int idGroup { get; set; }
public string name { get; set; }
public User owner { get; set; }
public List<User> members { get; set; }
public Group()
{
members = new List<User>();
}
}
And here is the insert group function :
[HttpPost]
public ActionResult Create(Group group)
{
if (ModelState.IsValid)
{
group.owner = db.Users.Attach((User)Session["user"]);
//Current user stored in session and already presents in User table
db.Groups.Add(group);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(group);
}
The problem is :
- When I run debugging into the insert function, the “owner” attribute is correctly set (at db.savechanges)
- But after, when I select a group in db (Group group =
db.Groups.Find(id);), the “owner” parameter is null.
Any help would be really appreciated.
Thanks a lot
Try this: