开发者

What is the right way to select/create sub objects with MVC /EF code first

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; }
    publi开发者_如何学运维c 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.


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


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)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜