Here I'm going to get last inserted auto-increment ID
for the Newstbl
. But here in the normal scenario we can take it as order by DESCENDING ORDER & get the first record.
But here I use ASP.NET MVC & Entity Framework, I'm stuck there. NewsId
is the auto-increment Id
My code:
public int GetLastInsertedId()
{
return (from x in context.Newstbl
orderby x.NewsId 'DESC'
select x)
}
IF you've properly set up your EF mapping, then basically when you insert a new NewsTbl
object, the auto-incremented ID
should be available as soon as you've called .SaveChanges()
on your context.
So if you do this:
using(YourEFContext ctx = new YourEFContext())
{
NewsTbl news = new NewsTbl();
// set some properties here on "news".....
ctx.NewsTbl.Add(news);
ctx.SaveChanges();
}
then after the call to .SaveChanges()
, your news
object should actually already contain the auto-incremented ID
property.... so I don't really understand why you're going through all this trouble of trying to read out the last inserted auto-increment ID
- it's already there for you, in your object.
you can get this way using Linq Method Query syntax:
public int GetLastInsertedId()
{
return context.Newstbl.OrderByDescending(x=>x.NewsId).First().NewsId;
}
and using query expression syntax:
public int GetLastInsertedId()
{
return (from x in context.Newstbl
select x).OrderByDescending(x=>x.NewsId).First().NewsId;
}
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.