开发者

Entity Framework error - nested model problem

I'm new to ASP.NET MVC and want to create a small order management tool. My database contains the tables Orders and Articles (and a few other ones), and I generated an EF Model from my database, so I can use the full power of the EF mappings (e.g. db.Orders.Articles)

My two main rela开发者_如何学运维tions which I'm concerned about are Orders and Articles.

  • An order can have many articles
  • An article can only belong to one order.

I've created an OrdersController with an Create action to create an order:

        //
    // GET: /Orders/Create

    public ActionResult Create()
    {
        Order order = new Order()
        {
           // filling some order columns, e.g. date
        };

        Article article = new Article()
        {
            // ... article columns
        };

        order.Articles.Add(article);

        return View(order);

    } 

    //
    // POST: /Orders/Create

    [HttpPost]
    public ActionResult Create(Order order)
    {
        // i know i should care more about error handling, but now ommit it
        db.Orders.AddObject(order);
        db.SaveChanges();

        return RedirectToAction("index");
    }

So I'm directly binding an EF Object to a view (read somewhere not to do that and use a view model instead, but don't really know what that view model should look like)

My view contains the Order form as well as the article form (because i want to create a order and articles at the same time and not seperate). I used these greate EditorFor Methods to do that.

And now to my problem: If i hit the submit button, the app crashes as soon as it comes to the HttpPost Create Method (when mapping the order) with this error message:

Error Message: The EntityCollection has already been initialized. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph.

If i hit continue in VS2010, it will complete saving the order - so my question is how to solve this problem in a reliable way.

Thanks in advance and sorry for that long story :)


I solved my problem now by using a separate ViewModel like @Yakimych advised me. However I did not copy all the attributes from the EF models, instead I just refer to them. My ViewModel looks like this:

public class NewOrderViewModel {
  public Order { get; set; }
  public List<Article> { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜