darkdog
darkdog

Reputation: 3995

c#: getting the last id of an entity (LINQ2SQL)

i looked a bit around stackoverflow to find an answer for my question. All what i found is this: Get Last ID From The table [ Entity Framework ]

This is exactly what i need.. but there is no answer for this question.. seems that the guy who asked the question didnt explain why he needs it.

I am coding a ticket system for my company.

Now if someone creats a ticket i want him not to type in the Ticket ID (Ticket #) by himself.. i want a textbox which is Enabled = false. It should automatically be filled with the new Ticket ID (it must be the last Ticket ID + 1).

This is the reason why i am looking for the last id of my entity.

i tryed out this:

var ticketNrQuery = (from tn in kdVerwaltung.Ticket
                     orderby tn.Ticket_ID
                     select tn).Last();
textBoxTicketNr.Text = (ticketNrQuery.Ticket_ID + 1).ToString();

in this sample i get an unsupported exception (what the hell).

Any solutions for my problem?

Upvotes: 1

Views: 2242

Answers (2)

Steav
Steav

Reputation: 1486

        Int32? newID = (from ticket in kdVerwaltung.Ticket select (int?)ticket.ID).Max();
        newID = newID.HasValue ? newID.Value + 1 : 1;

Upvotes: 1

alexn
alexn

Reputation: 58962

You can use MAX() since it can be translated to SQL:

var maxTicketId = kdVerwaltung.Ticket.Max(x => x.Ticket_ID) + 1;

That will be translated into the following query:

SELECT MAX([t0].Ticket_ID) as [value] FROM [dbo].[YourTable] AS [t0]

You should profile this if you're going to use it in production. Using MAX can be pretty slow if you have a lot of rows.

Upvotes: 2

Related Questions