Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to get newly created entry's Id, which is database generated

$
0
0

My app will display a bunch of uploaded product pictures, and these pictures will be stored in the "~/Pictures/ProductId/" folder, therefore I have to break my Create actions into two stages:

1. Enter all regular properties and insert them into the database. After insertion, I will have a database generated ProductId.

2. With ProductId at hand, I can generate a directory "~/Pictures/ProductId/", then I can upload my product pictures into this folder.

My question is how do I get this newly database generated ProductId? Since all other fields such as ProductName may not be unique, if I do a search based on any of these fields, the result may not be safe.

Here is what I have tried:

        public Product Insert(Product product)
        {
            Product p = (Product) _context.Add(product);
            _context.SaveChanges();
            return p;
        }

To ease the compiler's complaint on type casting - "(Product) _context.Add(product)" - in my Product.cs file, I added:

    public class Product
    {
        .....
        public static explicit operator Product(EntityEntry<Product> v)
        {
            return (Product) v;
        }

     }

The compiler doesn't complain, but at run time I got a stackoverflow  exception.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



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