Question

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..

Was it helpful?

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();

OTHER TIPS

I can't be done, what will you do, if two users at same time try to create products? Add images and then set relation with product.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top