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.