user695916
user695916

Reputation: 51

getting the ID of newly added recorded using linq to entities

Hi this is my first project using linq to entities. I've figured out how to create a new record I just need to get the ID that was assigned to it so I can use it as a FK in an extension table when I add the entries there. I'm allowing users to create request, the request can be for multiple pieces of equipment so I have a Request and RequestedEquipment table. Here is the code I'm using 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 request that was created so I can use it to Create the needed entries in the RequestedEquipment Table?

Upvotes: 5

Views: 6590

Answers (3)

החלקה יפנית
החלקה יפנית

Reputation: 11

Ryan and Mikecito are both right. However, if you need a generic 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);
    }
}

This way you can create any entity you need and by returning the newly created entity you find its new id. HTH.

Upvotes: 1

Ryan
Ryan

Reputation: 4668

You should be able to pull the ID value from your new Request object after the call to SaveChanges(), so something like:

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

SaveChanges() should save your new record to the database, and if the ID column is set as an identity column in the DB, that auto-generated ID should be passed back into your object via the entity framework.

Also just in case here's a blog post on an issue where the ID field wasn't getting updated automatically: http://dotnethacker.wordpress.com/2010/12/24/entity-framework-savechanges-doesnt-get-the-generated-identity-key/

Upvotes: 8

Mikecito
Mikecito

Reputation: 2063

I believe the object you create will have the ID field populated once you save changes.

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

Upvotes: 0

Related Questions