开发者

Using Linq to update a List<T> of objects to DB

I have a form that returns me a List of FlatSessie objects

in my edit view I edit a few FlatSessie's and get them returned to my Post method in that List object.

In my DB I have Sessies, which I map using Automapper to FlatSessie's and back

now I can not get linq to make the update to the DB for me.

the code:

    [HttpPost]
    public ActionResult Sessies(int id, int? modID, int? projID, string schooljaarparam, List<FlatSessie> sl) {
        if (ModelState.IsValid) {
            foreach (FlatSessie s in sl) { //i run over all FlatSessies which i get
                Models.Sessies ses = Mapper.Map<FlatSessie, Sessies>(s); 开发者_如何学JAVA// i map them to the Sessies object
                List<Sessies> origReeks = _db.Sessies.Where(p => p.Ses_ID == ses.Ses_ID).ToList(); //i get the original Session by ID. if there is a Session with that ID, if not (the ID will be 0) i do an Insert. if there is i want to do an Update.

                if (origReeks.Count > 0) {
                    //it's an update
                    UpdateModel(origReeks.First(); //doesnt work
                    //_db.Sessies.Attach(ses, origReeks.First()); //doesnt work, gives me an error on used ID...
                    _db.SubmitChanges();
                } else {
                    //no sessies yet, add them, this works.
                    _db.Sessies.InsertOnSubmit(ses);
                    _db.SubmitChanges();
                }
            }
            TempData["okmsg"] = "De sessies zijn opgeslagen";
            return RedirectToAction("Index");
        }

        //if not valid, i return the viewdata which i need.

        Module m = _db.Modules.First(md => md.Mod_ID == modID.Value);
        int antses = m.Mod_AantalSessies.Value;

        List<List<SelectListItem>> lpllst = new List<List<SelectListItem>>(antses);


        for (int i = 0; i < antses; i++) {
            lpllst.Add(MvcApplication.lesplaatsList(schooljaarparam, -1));
        }

        ViewData["lesplist"] = lpllst;
        ViewData["lglist"] = MvcApplication.lesgeverList();

        return View(sl);
    }


It might work to provide a prefix to UpdateModel (FlatSessie[n], where n is such that it matches the actual input name of the model element in question) so that it knows which properties to map onto the object, but because you are getting a list of these it might not. Have you tried updating the retrieved model using the data from the matching FlatSessie object directly?

Also, once you get this to work, you might want to do a single SubmitChanges for all inserts/updates (outside the loop) so that you get the entire submit wrapped in a single transaction. This will make it easier if there are errors to correct them and resubmit -- since you won't have some changes already committed causing further potential errors.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜