Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.Net Core Entity Framework FromSqlRaw perform insert and return Identity

I am doing an Asp.Net Core Application and I am using Entity Framework to performs Select, Insert and Update to the database.

I am using

_dbContext.Database.ExecuteSqlRaw(" insert into TEST3( Field) Values ('ok')");

and works fine…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I need to retrieve the @@Identity generated. So I run

query = "insert into TEST3( Field) Values ('ok'); Select @@IDENTITY as Id;"
T aa = await _dbContext.Set<T>().FromSqlRaw(query).FirstOrDefaultAsync();

T is a Model to get the Id

 public class InsertModel
    {
        [Key]
        public Int32 Id{ get; set; }
    }

I have this error

System.InvalidOperationException: ''FromSql' or 'SqlQuery' was called with non-composable SQL and with a query composing over it. Consider calling 'AsEnumerable' after the method to perform the composition on the client side.'

How can I perform the insert and return the ID?

Thanks

>Solution :

You can do this with ExecuteSqlRaw and an output parameter.

var pId = new SqlParameter("@rv", SqlDbType.Int);
pId.Direction = ParameterDirection.Output;
db.Database.ExecuteSqlRaw(" insert into TEST3( Field) Values ('ok'); set @id = scope_identity();", pId);
var id = (int)pId.Value;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading