1次操作获取EF的2次插入/添加的lastinsertedID

时间:2019-04-14 23:34:02

标签: c# entity-framework asp.net-mvc-5 identity

我有一个动作和2个SQL表,我知道如何在1个表中输入记录,但是对于第二个表,我想从表1中获取最后插入的ID,并将其插入第二列中的其中一个列。我已完成所有设置,但我的数据库保存无一例外都无法正常工作。我还不确定如何使用scope_identity()或获取最后的ID,而我正在使用EF进行所有操作。

public ActionResult AddTimeSheet()
        {
            ViewBag.ProjectsSelect = new SelectList(
                context.Projects.ToList(), "ProjectId", "ProjectName");

            var uid = User.Identity.GetUserId();
            ViewBag.CurrentId = uid;

            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddTimeSheet(TimeSheetProjectsModel timeSheetModel)
        {
            try
            {
                if(timeSheetModel == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                //if (ModelState.IsValid)
                //{
                    TimeSheetMaster masterModel = new TimeSheetMaster();
                    masterModel.FromDate = timeSheetModel.Proj1;
                    masterModel.ToDate = timeSheetModel.Proj1.AddDays(7);
                    /* NEED HRS 4 WEEK/END MONTH/NEW MONTH */

                    masterModel.TotalHours = timeSheetModel.ProjTotal1;
                    masterModel.UserId = User.Identity.GetUserId();
                    masterModel.DateCreated = DateTime.Now;
                    /* MONTH SUBMITTED */

                    masterModel.TimeSheetStatus = 1;
                    masterModel.Comment = timeSheetModel.ProjDesc1;
                    context.TimeSheetMaster.Add(masterModel);

                    var detailsModel = CreateTimeSheetDetails(masterModel, timeSheetModel);
                    context.TimeSheetDetails.Add(detailsModel);
                    context.SaveChanges();

                    TempData["SuccessMaster"] = "TimeSheetMaster Created Successfully";
                    TempData["SuccessDetails"] = "TimeSheetDetails Created Successfully";
                    return RedirectToAction("TimeSheetList", "TimeSheet");
                //}
               // TempData["Error"] = "TimeSheet Create Was Unsuccessful";
               // return RedirectToAction("TimeSheetList", "TimeSheet");
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                TempData["Error"] = "TimeSheet Create Was Unsuccessful";
                return RedirectToAction("TimeSheetList", "TimeSheet");
            }
        }

1 个答案:

答案 0 :(得分:0)

如果两个实体与同一个DbContext关联并且直接相关(PK / FK),则最佳解决方案是确保实体具有为该关系设置的导航属性,并让EF管理密钥和链接。

例如:

TimeSheetMaster masterModel = new TimeSheetMaster();
masterModel.FromDate = timeSheetModel.Proj1;
masterModel.ToDate = timeSheetModel.Proj1.AddDays(7);
masterModel.TotalHours = timeSheetModel.ProjTotal1;
masterModel.UserId = User.Identity.GetUserId();
masterModel.DateCreated = DateTime.Now;
masterModel.TimeSheetStatus = 1;
masterModel.Comment = timeSheetModel.ProjDesc1;

var detailsModel = CreateTimeSheetDetails(masterModel, timeSheetModel);
// either here, or inside CreateTimeSheetDetails...
// if Master has a collection of Details: (1-to-Many)
masterModel.Details.Add(details);
// or if Master has a 1-to-1 relationship to details.
// masterModel.Details = detailsModel;

context.TimeSheetMaster.Add(masterModel);

context.SaveChanges();

理想情况下,EF应该管理您的关系,以便您的代码可以简单地与相关实体结构配合使用,并将密钥/关系管理移交给Entity Framework。

如果您需要ID跨上下文,或者需要在执行插入操作后返回ID,则可以在调用SaveChanges之后直接访问实体的新PK:

context.TimeSheetMaster.Add(masterModel);
context.SaveChanges();
var newId = masterModel.TimeSheetMasterId; // Populated automatically after SaveChanges.