Jeyhun Rahimov
Jeyhun Rahimov

Reputation: 3787

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

Upvotes: 0

Views: 182

Answers (2)

webdeveloper
webdeveloper

Reputation: 17288

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.

Upvotes: 1

Tim S.
Tim S.

Reputation: 56556

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

Upvotes: 3

Related Questions