Search code examples
c#sql-server-2008asp.net-mvc-3-areas

How to know current new object's ID in advance, before saving?


In my ASP.NET MVC3 application (C#, SQL Server) Product has ImagePath as string type. When I save the image, I want to give product's ID value to ImagePath. When I create new product, I don't know what will be the current product's ID before db.SaveChanges();

 public ActionResult Create( Product product )
   { 
       .....
       .....//How to know ID of this product in advance?
       .....
       db.Products.AddObject( product );
       db.SaveChanges();
   }

I can find last item of products and increase it:

currentID = lastID + 1;

But, maybe the last ID was deleted. Result will not correct..


Solution

  • I'd suggest the following approach:

    //don't save the image yet, or save it in a temporary location
    db.Products.AddObject( product );
    db.SaveChanges();
    product.ImagePath = //path including product.Id
    //save or move image to product.ImagePath
    db.SaveChanges();