Вопрос

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