CRich
CRich

Reputation: 57

How to update an Entity in Entity Framework

I have a Date field in my DB and I'm trying to update it to the current Date when I press the submit button on my webpage but it does not update. I believe I'm doing the correct steps but here is my code.

Controller:

public ActionResult TakeInventory(int? AssetNum, string owners, string locationId, string clientId)
        {
            ViewBag.LocationId = new SelectList(db.Locations, "LocationKey", "LocationName");
            ViewBag.ClientId = new SelectList(db.ClientSites, "ClientSiteKey", "ClientSiteName");
            var records = from s in db.Assets select s;
            if (AssetNum != 0)
            {
                records = records.Where(c => c.AssetKey == AssetNum);
            }

            if (!String.IsNullOrEmpty(owners))
            {
                records = records.Where(x => x.InventoryOwner.Equals(owners));
            }

            if (!String.IsNullOrEmpty(locationId))
            {
                int locnum = Convert.ToInt32(locationId);
                records = records.Where(x => x.LocationKey == locnum);
            }

            if (!String.IsNullOrEmpty(clientId))
            {
                int clinum = Convert.ToInt32(clientId);
                records = records.Where(x => x.ClientSiteKey == clinum);
            }


            else
            {
                return View(records);
            }
            return View(records);

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult TakeInventory([Bind(Include = "InventoryDate")] Asset asset)
        {
            if (ModelState.IsValid)
            {
                db.Entry(asset).State = EntityState.Modified;
                asset.InventoryDate = DateTime.Now;
                db.Assets.Add(asset);
                db.SaveChanges();
                return RedirectToAction("Index");

            }
            return View(asset);
        }

View:

@foreach (var items in Model)
    {
        <p>Last Inventory Date: @Html.DisplayFor(modelItem => items.InventoryDate) </p>
        <input type="submit" value="Submit" />

Model:

public partial class Asset
    {    
public System.DateTime InventoryDate { get; set; }
    public Asset()
      {
      InventoryDate = DateTime.Now;
      }
    }

Upvotes: 0

Views: 62

Answers (3)

Ghanshyam Singh
Ghanshyam Singh

Reputation: 1381

Why you are passing the Current date , there is no need for that you can you Sql build in function "GETDATE()" to Get the current Date

Upvotes: 0

Ivan Mokrov
Ivan Mokrov

Reputation: 50

Is a bad practice: asset.InventoryDate = DateTime.Now;

At least, you need: 1. SaveChanges() your DbContext 2. Your DateTime field in backend must be Nullable or NotNull in Db (there is no inmpicit conversion)

But the real trouble is timezones. Its all works fine, if you have only one instance in only one datacenter and all your clients is from only one small and beauty country (one timezone wide)

DateTime.Now returns you local mashine timezone time.

If you use your 'entity.InventoryDate' in any kind of requests query it can return confused rezults, and can be surprized with funny result: for ex., value with tomorrow datetime relatively to you :)

For Web-services always cast to UTC that kind of fields, or use triggers or default expression for this kind of fields inside your DB engine

P.S. Russia is 11 timezones wide, i know what i'm talking about

Upvotes: 0

Win
Win

Reputation: 62260

You want to retrieve the Asset entity again before updating again.

For example,

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TakeInventory([Bind(Include = "InventoryDate")] Asset asset)
{
   if (ModelState.IsValid)
   {
      var entity = (from s in db.Assets where AssetNum == asset.AssetNum Select s).FirstOrDefalt();
      entity.InventoryDate = DateTime.Now;
      db.SaveChanges();
      return RedirectToAction("Index");
   }
   return View(asset);
}

Upvotes: 2

Related Questions