1

I am using MVC3 with Entity Framework Code First. I have the following model.

public class MyObject
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int MySubObjectId { get; set; }

    public virtual MySubObject MySubObject { get; set; }
}
public class MySubObject
{
    public int Id { get; set; }
    public string SubName { get; set; }
}

On my create page for MyObject, the user can either select an existing MySubObject to use, or create a new one (select or create is done w/ auto complete textbox in an edit template for MySubObject).

What is the proper way to handle this from a binding/controller perspective.

Should I use MySubObject.Id and create a new object if that Id is not valid? Should I just use the MySubObject.SubName and look up the Id when it gets posted back to the controller?

Everything I've come up with seems pretty messy on the controller side.

Josh
  • 2,259
  • 4
  • 22
  • 25

2 Answers2

0

You are passing text but to build your relation you need the Id so there is no other way then call something like:

var mySubObject = context.SubObjects.SingleOrDefault(o => o.Name == name);

If the return value is entity you can use it to build relation with existing sub object. If you get a null you know that you must create a new sub object. Simply by creating a new instance and assigning it to navigation property of the main object should force the insert.

Few notes:

  • If you want to do this, you should define unique key on the sub object's Name. EF doesn't support unique keys so you must do it directly in the database - for code first use custom database initializer.
  • Be aware that case sensitivity of name comparison will be based on the collation of the database
Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
0

The ViewBag can be used to store the select list that is then used in the view for a drop down box.

In the controller

ViewBag.MySubObjectId = new SelectList(db.MySubObjects, "MySubObjectId", "SubName", model.MySubObjectId);

Then in the view

@Html.DropDownList("MySubObjectId", String.Empty)
Josh
  • 2,259
  • 4
  • 22
  • 25