public IHttpActionResult PostCountry(Country country)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Country.Add(country);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = country.CountyID }, country);
}
Data is saving successfully but not displaying in database.
Here I attached the screen
Related
I had this code working - then I added the ability to add or update an image from the edit function - not when I add an image and try to update the sql record - it adds a new record. Here is the controller code for the edit. ANy ideas?
public ActionResult Edit(int id)
{
var Emp = db.Employees.Find(id);
if (Emp == null)
{
return HttpNotFound();
}
return View(Emp);
}
// POST: Employees/Edit/5
[HttpPost]
public ActionResult Edit(int id, Employee employee, HttpPostedFileBase image1)
{
try
{
if (image1 != null)
{
employee.Image = new byte[image1.ContentLength];
image1.InputStream.Read(employee.Image, 0, image1.ContentLength);
}
db.Entry(employee).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = id });
}
catch
{
return View();
}
}
When the line db.savechanges() hits the breakpoint. Nothing happens. no errors in the catch block. The browser just freezes and data is not saved. I am using oracle with asp.net mvc. my code is given below;
public ResponseResult AddUserPermission(USER_PERMISSION permission)
{
try
{
_db.Entry(permission).State = EntityState.Modified;
_db.SaveChanges();
return new ResponseResult();
}
catch (Exception ex)
{
//return new ResponseResult();
return new ResponseResult(ResutlType.Error, ex.Message);
}
}
And the controller calls the method is given below:
[HttpPost]
[CustomAuthorize("Admin")]
public ActionResult Create(USER model)
{
try
{
string moduleId = Request.Form["ModuleId"];
string isSelected = Request.Form["IsSelected"];
model.DATE_CREATED = DateTime.Now;
model.DATE_UPDATED = DateTime.Now;
model.STATUS = (int)Status.Active;
var userPermission = processPermissionData(moduleId, isSelected);
//userPermission contains a list of permissions which i am trying to save
_userService.Add(model);
foreach (var permission in userPermission)
{
_userService.AddUserPermission(permission);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I get no response from the browser or VS 15. All i get is the loading sign in the browser tab.
EDITED:
I have Created CRUD Functions for each Modals and now i am trying to get recent Inserted Id and use it in different view.
Here is what I have tried so far
I have created 2 classes(Layer based) for CRUD function for each ContextEntities db to practice pure OOP recursive approach and following is the code.
1. Access Layer
ViolatorDB
public class ViolatorDB
{
private TPCAEntities db;
public ViolatorDB()
{
db = new TPCAEntities();
}
public IEnumerable<tbl_Violator> GetALL()
{
return db.tbl_Violator.ToList();
}
public tbl_Violator GetByID(int id)
{
return db.tbl_Violator.Find(id);
}
public void Insert(tbl_Violator Violator)
{
db.tbl_Violator.Add(Violator);
Save();
}
public void Delete(int id)
{
tbl_Violator Violator = db.tbl_Violator.Find(id);
db.tbl_Violator.Remove(Violator);
Save();
}
public void Update(tbl_Violator Violator)
{
db.Entry(Violator).State = EntityState.Modified;
Save();
}
public void Save()
{
db.SaveChanges();
}
}
2. Logic Layer
ViolatorBs
public class ViolatorBs
{
private ViolatorDB objDb;
public ViolatorBs()
{
objDb = new ViolatorDB();
}
public IEnumerable<tbl_Violator> GetALL()
{
return objDb.GetALL();
}
public tbl_Violator GetByID(int id)
{
return objDb.GetByID(id);
}
public void Insert(tbl_Violator Violator)
{
objDb.Insert(Violator);
}
public void Delete(int id)
{
objDb.Delete(id);
}
public void Update(tbl_Violator Vioaltor)
{
objDb.Update(Vioaltor);
}
}
And Finally using Logic Layer functions in presentation Layer.Here insertion is performed as:
public class CreateViolatorController : Controller
{
public TPCAEntities db = new TPCAEntities();
private ViolatorBs objBs;
public CreateViolatorController()
{
objBs = new ViolatorBs();
}
public ActionResult Index()
{
var voilator = new tbl_Violator();
voilator=db.tbl_Violator.Add(voilator);
ViewBag.id = voilator.VID;
return View();
}
[HttpPost]
public ActionResult Create(tbl_Violator Violator)
{
try
{
if (ModelState.IsValid)
{
objBs.Insert(Violator);
TempData["Msg"] = "Violator Created successfully";
return RedirectToAction("Index");
}
else
{
return View("Index");
}
}
catch (Exception ex)
{
TempData["Msg"] = "Failed..." + ex.Message + " " + ex.ToString();
return RedirectToAction("Index");
}
}
}
Now here is the main part how do i get perticuller inserted id in another controller named Dues while performing insertion ?
In sqlqery I would have used ##IDENTITY but in Entity Framework I'm not sure.
I'm new to mvc framework any suggestion or help is appreciated Thanks in Advance.
Once you save your db context the id is populated back to your entity by EF automatically.
for example.
using(var context = new DbContext())
{
var employee = new Employee(); //this has an id property
context.Employees.Add(employee);
context.SaveChanges();
var id = employee.id; // you will find the id here populated by EF
}
You dont need to add and save your table as you have done this already in your voilatorDB class just fetch the last id like following
var id = yourTableName.Id;
db.yourTableName.find(id);
Or you can simply write one line code to achive that using VoilatorBs class function
GetbyID(id);
This my Code
Model
public class ViewModelRequestPurchaseItem
{
public List<RequestPurchase> RequestPurchases { get; set; }
public List<RequestPurchaseItem> RequestPurchaseItems { get; set; }
}
View
#using EFMySQLCardTest.Models
#model EFMySQLCardTest.Models.ViewModelRequestPurchaseItem
Controller
public ActionResult Edit([Bind(Include = "RequestPurchases,RequestPurchaseItems")] ViewModelRequestPurchaseItem viewModelRequestPurchaseItem, string id)
{
var requestPurchase = db.RequestPurchase.Where(x => x.RequestPurchaseNumber == id).ToList();
var requestPurchaseItem = db.RequestPurchaseItem.Where(x => x.RequestPurchaseNumber == id).OrderBy(x => x.RequestPurchaseItemID).ToList();
viewModelRequestPurchaseItem.RequestPurchases = requestPurchase;
viewModelRequestPurchaseItem.RequestPurchaseItems = requestPurchaseItem;
if (ModelState.IsValid)
{
db.Entry(viewModelRequestPurchaseItem).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
this.ExpendErrors();
}
return View(viewModelRequestPurchaseItem);
}
In this line:
db.Entry(viewModelRequestPurchaseItem).State = EntityState.Modified
the error is:
viewModelRequestPurchaseItem is not model of parts
ViewModelRequestPurchaseItem is your view model and is not part of the database context. You need to save each RequestPurchase and RequestPurchaseItems in the collections. You current code is also assigning the collections to the current values in the database, wiping out any edits you have made in the view. Your method should be
public ActionResult Edit(ViewModelRequestPurchaseItem model)
{
if (ModelState.IsValid)
{
return View(model);
}
foreach (RequestPurchase item in model.RequestPurchases)
{
db.Entry(item).State = EntityState.Modified;
}
// ditto for RequestPurchaseItems
db.SaveChanges();
return RedirectToAction("Index");
}
I have a small project in asp.net mvc 3 and I am using RavenDB to store data.
But when i am trying to update entity i have error saying
"Attempted to associate a different object with id 'orders/257'"
I have a service class to menage entities.
This is method to update entity called Order.
I'v omitted the rest of methods baceuse of clarity
public ErrorState UpdateOrder(Order order)
{
try
{
documentSession.Store(order);
documentSession.SaveChanges();
return new ErrorState { Success = true };
}
catch (Exception ex)
{
return new ErrorState { Success = false, ExceptionMessage = ex.Message };
}
}
This is rest of OrderRepository
private readonly IDocumentSession documentSession;
public OrderRepository(IDocumentSession _documentSession)
{
documentSession = _documentSession;
}
ErrorState class is for menagege errors in app, it contains bool success and string message of exception.
This is my edit Actions.
public ActionResult Edit(int id)
{
Order order = orderRepository.ObtainOrder(id);
if (order == null)
{
TempData["message"] = string.Format("Order no: {0} not found", id);
return RedirectToAction("Index");
}
return View(order);
}
[HttpPost]
public ActionResult Edit(Order order)
{
if(!ModelState.IsValid)
return View();
errorState = orderRepository.UpdateOrder(order);
if (errorState.Success)
{
TempData["message"] = string.Format("Order no: {0} has been changed", order.Id);
return RedirectToAction("Index");
}
else
{
TempData["Message"] = string.Format("Error on update order no: {0} MSG: {1}", order.Id,errorState.ExceptionMessage);
return RedirectToAction("Index");
}
}
This is the rest of the controller , I'v omitted the rest of actions baceuse of clarity.
private readonly IOrderRepository orderRepository;
private ErrorState errorState;
public HomeController(IOrderRepository _orderRepository,IDocumentSession _documentSession)
{
orderRepository = _orderRepository;
}
You already have an instance of an order with that id.
Check the session lifetime, is it possible that you have the same session across requests?