0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90

2 Answers2

3

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();
Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

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.

webdeveloper
  • 17,174
  • 3
  • 48
  • 47
  • Product can have maximum 5 images. And in every day product's images are saving to same folder. Tomorrow, to other folder. Customer want to watch that folder and delete any image he want. He want that I set relation between product and its images – Jeyhun Rahimov Sep 22 '12 at 12:22
  • @Mores Alternatively you can send data with ajax, receive id and give ability for image uploading. – webdeveloper Sep 22 '12 at 12:30