2

Sorry but i'm a beginner.

I have two classes: User and Group which are linked together (Group class have an User type attribute)

Here is User.cs :

public class User
{
    [Key]
    public int userId { get; set; }

    [Required]
    [MaxLength(10)]
    [Display(Name="Firstname")]
    public string firstname { get; set; }

    [Required]
    [MaxLength(10)]
    [Display(Name = "Lastname")]
    public string lastname { get; set; }
}

Here is Group.cs :

public class Group
{
    [Key]
    public int idGroup { get; set; }
    public string name { get; set; }
    public User owner { get; set; }
}

Here is the insert

private myContext db = new myContext();
[HttpPost]
    public ActionResult Create(Group group)
    {
        group.owner = (User)Session["user"];
        if (ModelState.IsValid)
        {
            db.Groups.Add(group);
            db.SaveChanges();
            return RedirectToAction("Index","Home");
        }

        return View(group);
    }
//Session["user"] contains an User type object (which is already in database)

The problem is : When I add a new group, it automatically inserts a new User into the databae, instead of JUST inserting the corresponding group.

Example : I am "user1" (so "user1" is present in the User table) and I want to create the "group1" group. I link the user I am with the "owner" attribute of the Group class.

group1 will be inserted into Group table but user1 will be also inserted into the User table.. That will cause a duplicate content

I don't know how to avoid this...

Any help would be appreciated.

4

2 に答える 2

0

Try this, Assuming that a Group can have more than one User.

using (DbEntities ctx = new DbEntities())
{
    // Create new Group
    Group g = new Group() { name = "Some name", };

    //Create new User 1
    User u1 = new User() { firstname = "user 1", };

    //Create new User 2
    User u2 = new User() { firstname = "user 2", };

    // Add users to the Group
    g.owner.Add(u1);
    g.owner.Add(u2);

    //Updating the context
    ctx.AddToGroup(g);

    //Save to Database
    ctx.SaveChanges();
}
于 2012-11-16T18:14:12.727 に答える
0

You'll have to attach your existing User to your DbContext instance using Attach. This will prevent EF to create a duplicate of the object.

于 2012-11-16T20:17:11.580 に答える