0

I am saving multiple photos to same pr_id into database. Each details are entering as different rows. So while retrieving I need the highest or last entered photo_id for each pr_id. How do I do that in C#?

My database table looks like this:

enter image description here

My view code :

    @if (Model.Photos.Count > 0)
    {
        <div>
            @foreach (var photo in Model.Photos)
            {
             @{ var last = Model.Photos.Last(); }
                @Html.EditorFor(modelItem => last.photo_id)
        </div>
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Do you want the id returned when you `INSERT`? Is it an identity column/table? – maccettura Jun 13 '18 at 18:44
  • Do you have Identity (auto generation of PK values) enabled in your table ? How are you inserting your record ? – Shyju Jun 13 '18 at 18:45
  • Yes i need to return id –  Jun 13 '18 at 18:46
  • photo_id is auto is auto generated value –  Jun 13 '18 at 18:47
  • What have you tried so far? StackOverflow is not a code-generation service. Rather, we're here to point you in the right direction when you've made a concerted effort and you are stuck. – David L Jun 13 '18 at 18:48
  • You can get the identity field value back from your insert query. look at the example somewhat described here: https://stackoverflow.com/questions/14246744/executescalar-vs-executenonquery-when-returning-an-identity-value – The Lyrist Jun 13 '18 at 18:51
  • What is inside `Model.Photos` ? Is it all the Photos (for all Pr_id) or just the photos for a specific Pr_Id ? – Shyju Jun 13 '18 at 19:35
  • its all the photos for all pr_id –  Jun 13 '18 at 19:45
  • What is your expected output ? You want to show all the PR_IDs and it's last photos ? Or you want to simply show the last photo( from all photos) ? – Shyju Jun 13 '18 at 20:00
  • I want to show all the pr_ids and its last photo. –  Jun 13 '18 at 20:05
  • Do the insert through a stored procedure that also returns the last inserted it. – yogihosting Jun 13 '18 at 20:15

1 Answers1

0

If you are trying to show all the pr_ids and it's last photo, you should do a group by on your Model.Photos collection and then do an OrderBy on the grouped items and call the Last method.

@{
    var grouped = Model.Photos.GroupBy(a => a.pr_id);
}
@foreach(var item in grouped)
{
    <p>@item.Key</p>
    <span>@item.OrderBy(a=>a.photo_id).Last().Path</span>
}

Here we are simply printing the Key of the grouped item which is the pr_id. If you want more properties of the pr entity, create a class representing that data and use that in your LINQ group by statement.

Assuming Model.Photos is all the photo records for all the pr_ids

Shyju
  • 214,206
  • 104
  • 411
  • 497