我有一个简单的asp.net mvc3项目,包含实体框架4.1。 我问过上一个问题,答案很顺利 - How to correctly override the SaveChanges function in EF 4.1 date和loggedby的值在类构造函数中设置。这对于Create操作很好,但是当我使用Edit操作时,我看到日期和LoggedBy字段已更改,这是我不想要的。我也看到Delete不起作用 - 我猜这是因为构造函数。 如何解决这个问题,以便我的Date和LoggedBy值设置为Create但在Edit期间没有更改? 乙
using System;
using System.Collections.Generic;
using System.Web;
public partial class tblDefectDetail
{
public tblDefectDetail()
{
DateLogged = DateTime.Now;
LoggedBy = HttpContext.Current.User.Identity.Name;
}
public int ID { get; set; }
public int Project { get; set; }
public string LoggedBy { get; set; }
public System.DateTime DateLogged { get; set; }
public string Issue { get; set; }
我的行动看起来像这样:
public ActionResult Create()
{
ViewBag.BugLocation = new SelectList(db.tblBugLocations, "ID", "BugLocation");
ViewBag.BugType = new SelectList(db.tblBugTypes, "ID", "BugType");
ViewBag.BusinessUnit = new SelectList(db.tblBusinessUnits, "ID", "BU_Name");
ViewBag.BugFoundMethod = new SelectList(db.tblDefectDiscoveryMethods, "ID", "DiscoveryMethod");
ViewBag.Project = new SelectList(db.tblProjects, "ID", "ProjectName");
ViewBag.Language = new SelectList(db.tblLanguages, "ID", "Language");
return View();
}
答案 0 :(得分:1)
不是在构造函数中设置值,而是在Action方法中设置它们。因此,在将模型传递给视图之前,请在“创建操作方法”中设置所需的值。
public ActionResult Create() {
var model = new tblDefectDetail() { LoggedBy = User.Identity.Name, DateLogged = DateTime.Now }
return View(model);
}