Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

Obtain next primary key value (for bigint/int) for SQL table in MVC app?

$
0
0

So I'm working on an MVC app and need to figure out how (using C# code within my controller class) to obtain the next available primary key for a table?

In my table, I have a primary key field setup, as follows:

ProductionEntryID BIGINT IDENTITY(1,1) PRIMARY KEY

Now, in my controller class, in the Create method (which I am using an out-of-box Create method scaffolded by VS), I need to figure out a way to generate the primary key (or obtain it some how) before the app calls the db.SaveChanges() method.

Any idea on how to do this?  This app will be used internally by my company, so I'm thinking that as far as getting an ID, and the risk of it not being available due to another user grabbing the ID and inserting data before the first person, is not going to be much of an issue.

Ideally, I'd like to have to not "calculate" or obtain this value, and just feed the other values that are required to INSERT a row in the table, and let SQL Server take care of assiging a primary key on its own, which I thought i could do by just specifying the required fields in my table (ie. non-null fields) and just issue an INSERT command and SQL Server will give the row its own primary key, but apparently I cannot seem to be able to do that from within ,my Create method in my controller because it calls db.Savechanges() (where db is the name of the database context).

Here is where I need to get the PK... before db.SAvechanges is called:

if (ModelState.IsValid)
{
db.ProductionEntries.Add(productionEntry);
db.SaveChanges();
return RedirectToAction("Index");
}

I can manually enter the primary key value if I include the appropriate field and textbox in the view that is rendered when the Create view is called, but I want this to be automatic so the user doesn't have to specify or even see) the ProductionEntryID field.  So, I've removed the textbox from the Create view, but it still exists in the data model entity definition that VS uses to communicate with the database.


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>