문제

I have a model with a property called "datetime_inclusion" and I need to set a value for this ONLY when I save the first time, there is a way to do this treatment in the model? I use C# MVC5 and entity framework 5

도움이 되었습니까?

해결책

When you save the first time your object won't have an ID until it gets put into the DB. You can check against this to set your value.

if(myEntity.ObjectID <= 0)
{
    myEntity.DateAdded = DateTime.Now;
}

다른 팁

Shoe's answer is perfect. But if you are worry that property can be change in edit time, control that. In create action use Shoe's code and in Edit action use:

[HttpPost] 
public ActionResult Edit(int id, Model model) 
{ 
     using (var db = new YourEntities()) 
     { 
         //control that, it does not change
         model.datetime_inclusion = db.YourTable.Find(id).datetime_inclusion;

         db.Entry(model).State = System.Data.EntityState.Modified; 
         db.SaveChanges(); 
         return RedirectToAction("Index"); 
     } 
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top