1

Given the following two models:

public class Card
{
    public int CardId { get; set; }

    public Media Media { get; set; }
}

public class Media
{
    public int MediaId { get; set; }

    [Required]
    public string FileName { get; set; }
}

And the following controller method:

[HttpPost]
public ActionResult Create(Card card)
{
    db.Media.Attach(card.Media);

    ModelState.Remove("Media.FileName");

    if (ModelState.IsValid)
    {
        db.Cards.Add(card);                
        db.SaveChanges();
    }

    return JsonNetSerializedResult(card);
}

I want to create a new Card, but associate it with an existing Media object. I POST to "Controller/Create" and include a "Media.MediaId" parameter that contains the ID of the existing Media record and let EF make the association.

However, after SaveChanges() is called, the only property updated on the Card instance is the CardId. I also need to retrieve the Media.FileName and set that property on the Card instance.

Is there a generic way to tell EF that I want return the updated Card data, and to also return the associated Media data commiting the data?

jkappers
  • 103
  • 1
  • 9

1 Answers1

1

What may be causing some confusion is the fact that you are using your Entity Model as your ViewModel.

I would actually recommend creating real ViewModel classes that represent the information received by the Controller or used as model to the views. Not using the entity model as is. It seem like extra work, but it does give you a lot more control over what the UI manages and how the entities are modeled.

In that case you would have maybe something like a NewCardModel or just simply CardModel, that has properties for the fields displayed in the UI, as well as the id of the Media element.

Then you'd have to manually create the Card instance, populate the information (automapper can be of great help), and you would need to look up your Media instance by ID and associate that instance to the new Card instance prior to saving your changes.

This SO answer may shed some more light on the pros and cons of using ViewModels: https://stackoverflow.com/a/10928437/1373170

Community
  • 1
  • 1
Pablo Romeo
  • 11,298
  • 2
  • 30
  • 58
  • Thanks for the suggestion, but the code in this example is more of an API, is view agnostic, and is so incredibly small and singularly focused that view models would add unnecessary overhead for this specific project. I just want to know if there is an easy and generic way to tell EF to repopulate the new model and also include the child model data when it returns. – jkappers Oct 18 '12 at 21:19
  • Now, even-though I don't think it would be the right approach, you can probably instead of returning "card" fetch it again by card.CardID from the context and return that. – Pablo Romeo Nov 02 '12 at 05:26