简体   繁体   English

MVC3 EF4在保存时复制外键对象

[英]MVC3 EF4 duplicates foreign key object on save

I'm using MVC3 with EF4 code-first. 我使用的是EF4代码优先的MVC3。 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. 当我尝试保存具有specificEventId = 2specificEvent = X的Order对象时,即使在数据库中已经存在ID为2的特定事件X,也会在数据库中创建一个新的SpecificEvent对象。 When i try with specificEventId = 2 and specificEvent = null I get a data validation error. 当我尝试使用specificEventId = 2specificEvent = null出现数据验证错误。

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'. 我希望SpecificEventSeasonalTicket是可为空的,并且我不希望EF4在保存“ Order”时在数据库中创建这些对象的新实例。

Update 更新资料

This is my code for saving Order in the DB: 这是我在数据库中保存Order代码:

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. 保存后,我确实到达了else子句。

The real question is, where did you get the instance of X from? 真正的问题是,您从哪里获得X的实例? It appears as though EF has no knowledge of this instance. 似乎EF不了解该实例。 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. 您要么需要通过EF获取已经存在的SpecificEvent,然后使用它返回的代理来设置导航属性,要么告诉EF“附加” X,以便它知道您的意图。 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. 据EF所知,它似乎是在尝试向其发送具有冲突ID的新实例,因此它正确地发出了错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM