kenp
kenp

Reputation: 500

Return an Object from Database.SqlQuery

There's a way with Database.SqlQuery to return the new object created ?

With Linq I do it this way :

Category category
db.Categories.Add(category);
db.SaveChanges();
return category;

Now category is an object that return the new category created with the new id.

How to do it with SqlQuery?

 return db.Database.SqlQuery<Category>("INSERT INTO " + categoryTable + " (title,description) VALUES ({0},{1}) ", category.title, category.description);

It returns a empty array but i want to return the new category created with the new id.

Thank you.

Upvotes: 0

Views: 75

Answers (1)

Fede
Fede

Reputation: 4016

I'm guessing you need this because Category has an autonumber Id property of some kind. Haven't tested this myself, but maybe you can get that to work by using the output clause of the insert statement. e.g.

return db.Database.SqlQuery<Category>("INSERT INTO " + categoryTable + " (title,description) OUTPUT inserted.id, inserted.title, inserted.description VALUES ({0},{1}) ", category.title, category.description);

Upvotes: 1

Related Questions