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?
after inserting the record into database it returns your record with created Id. You don't need to call any other method to get the id, you already got that after successful insertion so check your object which you passed in you "InsertOnSubmit" method. Here Customers is your table name.
LINQ Syntax - Fluent vs. The . First() method does just what you think it does – it gets the first element in the list.
The DbSet class is derived from IQuerayable . So, we can use LINQ for querying against DbSet , which will be converted to an SQL query. EF API executes this SQL query to the underlying database, gets the flat result set, converts it into appropriate entity objects and returns it as a query result.
LINQ Include allows retrieving the related entities to be read from database in same query. By using the Include method we can easily read all related entities from the database in a single query.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With