Ofirov
Ofirov

Reputation: 773

MVC3 EF4 duplicates foreign key object on save

I'm using MVC3 with EF4 code-first. I have the following model:

public class Order {

    public int ID { get; set; }

    [Required]
    public float Price { get; set; }

    [Required]
    public int PayMethodId { get; set; }
    public PayMethod PayMethod { get; set; }

    public int? SpecificEventId { get; set; }
    public SpecificEvent SpecificEvent { get; set; }

    public int? SeasonalTicketId { get; set; }
    public SeasonalTicket SeasonalTicket { get; set; }
}

When I try to save an Order object with specificEventId = 2 and specificEvent = X, a new SpecificEvent object is created in the DB, even though there's already a specific event X with ID 2 in the DB. When i try with specificEventId = 2 and specificEvent = null I get a data validation error.

What am I doing wrong? I want SpecificEvent and SeasonalTicket to be nullable, and I don't want EF4 to create a new instance of these objects in the DB whenever I save 'Order'.

Update

This is my code for saving Order in the DB:

public void SaveOrder(Order order)
{
    Order fromDb = null;

    // If editing an existing object.
    if ((fromDb = GetOrder(order.ID)) != null)
    {
        db = new TicketsDbContext();
        db.Entry(order).State = System.Data.EntityState.Modified;
        db.SaveChanges();
    }
    // If adding a new object.
    else
    {
        db.orders.Add(order);
        db.SaveChanges();
    }
}

When I save, I do reach the else clause.

Upvotes: 0

Views: 389

Answers (1)

Brian Kretzler
Brian Kretzler

Reputation: 9938

The real question is, where did you get the instance of X from? It appears as though EF has no knowledge of this instance. You either need to fetch the already existing SpecificEvent through EF and use the proxy it returns to set your navigation property, or else tell EF to "attach" X, so that it knows what your intent is. As far as EF knows, it appears, you are trying to send it a new instance with a conflicting Id, so it is properly issuing the error.

Upvotes: 1

Related Questions