Tang
Tang

Reputation: 685

Entity framework relationships

I have a problem with relationships in Entity-framework

Here is my problem :

I have two classes : User and 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 :

Any help would be really appreciated.

Thanks a lot

Upvotes: 1

Views: 198

Answers (2)

deerchao
deerchao

Reputation: 10544

Try this:

public class Group
{
    [Key]
    public int idGroup { get; set; }
    public string name { get; set; } 
    public virtual User owner { get; set; }
    public virtual ICollection<User> members { get; set; }

    public Group()
    {
        members = new List<User>();
    }
}

Upvotes: 1

Ashkan
Ashkan

Reputation: 636

This might solve your problem Group group = db.Groups.Find(id).Include("owner");

Upvotes: 0

Related Questions