Home > Net >  How can we get list of IDs of last inserted set of rows using C# and EF Core
How can we get list of IDs of last inserted set of rows using C# and EF Core

Time:05-21

I have a set of images and I tried to add them into a table (ImageGalleries) using EF Core. The insertion goes well. After the insertion I need IDs (there is an identity column in the table) of inserted records. I tried below post in StackOverflow. But I couldn't get reach.

get ids of inserted rows

public ActionResult Save(IEnumerable<IFormFile> images,RoomGalleryVM vm)
        {
            if (images!= null)
            {
                string fileName = "";
                foreach (var image in images)
                {
                    var fileContent = ContentDispositionHeaderValue.Parse(image.ContentDisposition);
                    fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
                    var gallery = new RoomGallery()
                    {
                        RoomId = vm.RoomId,
                        Description=fileName,
                        Status="A"
                    };
                    Context.RoomGalleries.Add(gallery);
                }
                Context.SaveChanges();
                //var Ids = vm.Select(c => c.Id).ToList();
            }
            return View("RoomGalleryIndex");
        }  

RoomGalleryVM

 public class RoomGallery
    {
        public int Id { get; set; }
        public int RoomId { get; set; }
        public Room Room { get; set; }
        [StringLength(100)] public string Description { get; set; }
        [StringLength(10)] public string Status { get; set; }
    }

Index page

<form method="post" asp-action="Save" asp-controller="RoomGallery">
<h6 style="margin-top: 2em;">Room:</h6>
    @(Html.Kendo().DropDownList()
            .Name("RoomId")
            .HtmlAttributes(new { style = "width:100%" })
            .OptionLabel("Select room...")
            .DataTextField("RoomName")
            .DataValueField("Id")           
            .DataSource(source =>
            {
                source.Read(read =>
                {
                    read.Action("GetRooms", "Reservation");
                })
                .ServerFiltering(true);
            })
            .Enable(false)
            .AutoBind(false)
    )
    <br />    
    <div >
        @(Html.Kendo().Upload()
            .Name("images")
            .HtmlAttributes(new { aria_label = "files" })
        )
        <p style="padding-top: 1em; text-align: right">
            <button>Submit</button>
        </p>
    </div>
</form>

CodePudding user response:

Just remember all the gallery you make, and retrieve their Id after you save:

            var newRGs = new List<RoomGallery>();
            foreach (var image in images)
            {
                var fileContent = ContentDispositionHeaderValue.Parse(image.ContentDisposition);
                fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
                var gallery = new RoomGallery()
                {
                    RoomId = vm.RoomId,
                    Description=fileName,
                    Status="A"
                };
                Context.RoomGalleries.Add(gallery);
                newRGs.Add(gallery);
            }

Then you can get the IDs for whatever you need after you have saved (the value the db calculated will be patched back into the local object)

var ids = newRGs.Select(rg => rg.Id).ToList();

If you want to use them in your view, don't forget to patch them back into your view model (what you want to use them for is unclear to me; the main point of this answer is "if you remember which objects you add to a context before you save then you can enumerate them for any db calculated values after you have saved")

CodePudding user response:

Update your code to below,

public ActionResult Save(IEnumerable<IFormFile> images,RoomGalleryVM vm)
    {
        List<int> Ids=new List<int>();
        if (images!= null)
        {
            string fileName = "";
            foreach (var image in images)
            {
                var fileContent = ContentDispositionHeaderValue.Parse(image.ContentDisposition);
                fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
                var gallery = new RoomGallery()
                {
                    RoomId = vm.RoomId,
                    Description=fileName,
                    Status="A"
                };
                Context.RoomGalleries.Add(gallery);
                Context.SaveChanges();
                Ids.Add(gallery.Id)
            }
        }
        var data = Ids; // here you will get list of ids
        return View("RoomGalleryIndex");
    }
  • Related