Getting id of newly added record using linq for objects

Hi, this is my first project using linq for entities. I figured out how to create a new record, I just need to get the identifier that was assigned to it, so I can use it as FK in the extension table when I add records there. I allow users to create a request, the request can be for several pieces of equipment, so I have a Request and RequestedEquipment table. Here is the code I use to create the request:

public void addReq(ReqType reqType, Employee reqBy, Location loc, string comm) { int reqID; Request req = new Request(); req.Comments = comm; req.Employee = reqBy; req.ReqType = reqType; req.RequestStatus = findReqStat(1); req.Location = loc; entities.AddToRequests(req); entities.SaveChanges(); } 

How can I get the id of the created request so that I can use it to create the necessary records in the RequestedEquipment table?

+4
source share
3 answers

After calling SaveChanges (), you will need to pull the ID value from your new Request object, so that:

 entities.SaveChanges(); reqID = req.ID; 

SaveChanges () should save your new record in the database, and if the identifier column is set as the identifier column in the database, this automatically generated identifier should be returned back to your object through the entity infrastructure.

Also, just in case, there is a blog post about a problem when the ID field was not updated automatically: http://dotnethacker.wordpress.com/2010/12/24/entity-framework-savechanges-doesnt-get-the-generated-identity- key /

+8
source

Ryan and Miketito are both right. However, if you need a general solution, take a look at the following function:

 public static T AddEntity<T>(T ent) { Type t = typeof(T); try { using (Entities be = new Entities()) { be.AddObject(t.Name, ent); be.SaveChanges(); return ent; } } catch (Exception) { return default(T); } } 

Thus, you can create any object that you need, and returning the newly created object, you will find its new identifier. NTN.

+1
source

I believe that the created object will have an identifier field populated after saving the changes.

So, after the line SaveChanges () check the value of the ID field.

0
source

All Articles