I am using Entity Framework with a Oracle Database for an MVC5 application. For my Controller action where I create a new Vendor entity, I have the below:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,vendor_name,created_date,created_by,modified_date,modified_by")] INV_VENDORS iNV_Vendors)
{
if (!db.INV_VENDORS.Any(m => m.VENDOR_NAME == iNV_Vendors.VENDOR_NAME))
{
//decimal id = db.INV_VENDORS.Last().ID + 1;
//iNV_Vendors.ID = db.INV_VENDORS.Last().ID + 1;
iNV_Vendors.CREATED_DATE = DateTime.Now;
iNV_Vendors.CREATED_BY = System.Environment.UserName;
ModelState.Clear();
TryValidateModel(iNV_Vendors);
if (ModelState.IsValid)
{
db.INV_VENDORS.Add(iNV_Vendors);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
}
else
{
ModelState.AddModelError("vendor_name", "The Vendor [" + iNV_Vendors.VENDOR_NAME + "] already exists in the table.");
}
return View(iNV_Vendors);
}
When I load the view and enter a value (say, "TEST") the code from breakpoint executes all the way down to await db.SaveChangesAsync(); where it throws the error Oracle.ManagedDataAccess.Client.OracleException
ORA-00001: unique constraint (INVENTORY.PK_INV_VENDORS) violated ORA-06512.
I'm not quite sure why I am getting this error, as the database has a Trigger to auto-increment the ID field value each time there is a new INSERT:
CREATE OR REPLACE TRIGGER INV_VENDORS_TRG
BEFORE INSERT
ON INVENTORY.INV_VENDORS
REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
BEGIN
-- For Toad: Highlight column ID
:new.ID := INV_VENDORS_SEQ.nextval;
END INV_VENDORS_TRG;
/
In my INV_VENDORS class of my DAL folder, I have tried specifying the [DatabaseGenerated] option for my ID field, but still receive the same error when trying to create a new VENDOR entity:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public decimal ID { get; set; }
Through testing it seems that Entity Framework is auto-setting the iNV_Vendors.ID value in my Controller code as 0, which is causing the duplication error -- the table already contains values with ID 1-23 currently.
Does anyone know how to query the database via linq for the last ID value in the table so that I can specify iNV_Vendors.ID as the returned value + 1? (Or perhaps a correct way around this should this be a bad idea?)