简体   繁体   中英

Updating Model with Not Mapped property in Entity Framework

I have this scenario where my model contain one propery which is not mapped , but its mendatory for the model as i am getting this as input from user, now when i want to update this model(table) i get exception for this property , that it cannot be null.

[NotMapped]
[Required(ErrorMessage = "Please Enter UserName")]
public string UserName { get; set; }

my Code when i want to update few fields, i am assigning username with value, which i don't think so i should. This User Name value is not affecting anything , but curious if there is a way to not modify it.

Orders order;
order = db.Orders.FirstOrDefault(o => o.ID.CompareTo(model.OrderID) == 0);
      if (order == null)
          {
             throw new Exception(Resources.WrongOrderID);
          }
     else
          {
             order.Order_Status = 1;
             order.Close_Order_User_ID = cmuser.ID;
             var dateQuery = db.Database.SqlQuery<DateTime>("SELECT NOW()");
             DateTime serverDate = dateQuery.AsEnumerable().First();

             order.Close_Order_Date = serverDate;
             order.UserName = cmuser.USER_NAME;
             db.Entry(order).State = EntityState.Modified;

             //db.Entry(order).Property(o => o.UserName).IsModified = false;

            db.SaveChanges();

            return Ok(Resources.OrderClosed);

   }

in the above code there is one commented line, i tried this but it will give exception of that "Is Modified cannot be used for the property which dont belong to model"

Do i have to add something in my function check below:

[Route("CloseOrder")]
public IHttpActionResult CloseOrder([something over here??]CloseOrderBinding model)

Please Advise.

If I understand correctly you need this:

public IHttpActionResult CloseOrder([[Bind(Exclude = "UserName")]CloseOrderBinding model)

and

ViewData.ModelState.Remove("UserName");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM