Is there a better way to add a child record using MVC 4 and Entity Framework 5?

[亡魂溺海] 提交于 2019-12-05 15:54:38

If you're using 'code first' (all things suggest), then you can do something like...

public class ContestPrize
{
    public long ID { get; set; }

    public long ContestID { get; set; }
    public Contest Contest { get; set; }
}

That should create (by convention) and map the ContestID to the FK. In some complicated cases you may need to specify that relationship in the fluent code, but this should suffice normally.

Then you can just reference the parent by ContestID - fill that in - and do Add.

That's in rough strokes, let me know if you need more info.

You probably shouldn't be using entities as view models directly. I suggest using something like this:

// Entitiy Type
public class ContestPrize { ... }

// ViewModel Type
public class ContestPrizeViewModel { ... }

// In your controller
[HttpPost]
public ActionResult Create(int ParentID, ContestPrizeViewModel ContestPrize)
{
    if (ModelState.IsValid)
    {
        var entity = db.Create<ContestPrize>();
        entity.ContestID = ParentID;
        entity.Blah = ContestPrize.Blah
        db.ContestPrizes.Add(entity);
        db.SaveChanges();
        return RedirectToAction("Index", "Contests", ParentID);
    }

    return View(ContestPrize);
}

This allows you to easily separate your domain logic from your view logic. It may require extra code, but it's a much more robust way of doing things.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!