Reputation: 37
I´m trying to do 2 linq insert queries. The second one needs the last inserted id value from the first query.
How can I get the last_id_inserted (last_fich)?
db.CWC_FICHEIROS.Add(new CWC_FICHEIROS
{
idfiletype = newextID,
filename = fileName,
fileurl = fileName,
fileordem = "AA001",
filedate = System.DateTime.Now,
fileact = true
});
last_fich = db.CWC_FICHEIROS.Max(item => item.id_file);
db.CWC_FILESSUBCONTEUDOS.Add(new CWC_FILESSUBCONTEUDOS
{
idfile = last_fich,
idsubconte = cwc_subconteudos.idcont,
fscact = true
});
db.SaveChanges();
Like it is, last_fich
gives me the id of the first row of CWC_FICHEIROS
.
Upvotes: 1
Views: 13252
Reputation: 223207
Instead of adding an object directly, create your object first and then insert like:
var yourOjbect = new CWC_FICHEIROS
{
idfiletype = newextID,
filename = fileName,
fileurl = fileName,
fileordem = "AA001",
filedate = System.DateTime.Now,
fileact = true
};
db.CWC_FICHEIROS.Add(yourObject);
db.SaveChanges();
Later you can access its ID as:
Console.WriteLine(yourObject.ID);
Do not rely on db.CWC_FICHEIROS.Max
, there could be multiple inserts in the database at the same time and you could end up with the wrong ID.
Upvotes: 5