drewwyatt
drewwyatt

Reputation: 6027

The relationship between the two objects cannot be defined - why?

I am submitting a form that contains a user id and a pipe-delimited set of numbers.

The model looks like this:

public class SeasonPassData
{
    public int UserID { get; set; }
    public string SpaceNumbers { get; set; }
}

That is getting handed off to this controller:

[HttpPost]
public ActionResult SignUp(SeasonPassData data)
{
    var user = db.Users.Find(data.UserID);
    List<SeasonPass> passes = new List<SeasonPass>();

    char[] delimiter = { '|' };
    var numbers = data.SpaceNumbers.Split(delimiter).Select(n => Convert.ToInt32(n)).ToArray();
    foreach(int number in numbers)
    {
        passes.Add(new SeasonPass { SpaceNumber=number, User = user });
    }
    passes.ForEach(p => db.SeasonPasses.Add(p));
    db.SaveChanges();

    return RedirectToAction("Confirmation", "Home");
}

And should be creating and saving SeasonPasses:

public class SeasonPass
{
    public int ID { get; set; }
    public int SpaceNumber { get; set; }

    public virtual User User { get; set; }
}

However, this - passes.ForEach(p => db.SeasonPasses.Add(p)); keeps raiding this exception:

An exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll but was not handled in user code

Additional information: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

How do I fix that?


I tried it with these changes based on a comment. It still doesn't seem to work...

[HttpPost]
public ActionResult SignUp(SeasonPassData data)
{
    using(var context = new TTUContext())
    {
        var user = context.Users.Find(data.UserID);
        List<SeasonPass> passes = new List<SeasonPass>();

        char[] delimiter = { '|' };
        var numbers = data.SpaceNumbers.Split(delimiter).Select(n => Convert.ToInt32(n)).ToArray();
        foreach (int number in numbers)
        {
            passes.Add(new SeasonPass { SpaceNumber = number, User = user });
        }
        foreach (var pass in passes)
        {
            context.SeasonPasses.Add(pass);
        }
        context.SaveChanges();
    }

    return RedirectToAction("Confirmation", "Home");
}

Upvotes: 0

Views: 247

Answers (1)

Jeremy Cook
Jeremy Cook

Reputation: 22063

I'm surprised that what you are doing does not work, but here is a way to sidestep the issue.

Add public int UserID { get; set; } to SeasonPass and set it to assign the relationship instead of setting User.

Upvotes: 1

Related Questions