0

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.

5
  • You could also just put: db.Database.Log=Debug.WriteLine; before you did your LINQ, and see what it generates. Commented Dec 10, 2015 at 20:18
  • Why use SqlQuery? It should be possible with Linq. Please see here: stackoverflow.com/questions/788320/… Commented Dec 10, 2015 at 20:20
  • Because i didnt find a way with LINQ to use a dynamic table. ex : categoryTable. And i want to avoid the use of conditions like : if, case, etc Commented Dec 10, 2015 at 20:23
  • 1
    Lol, you are probably the same guy who asked the other questions. You can also do (from my previous answers): db.GetTable("yourtable").Add(category); db.SubmitChanges(): Commented Dec 10, 2015 at 20:31
  • Lol, hey i opened a chat room with you ! By the way i will always need to use the conditions ! Commented Dec 10, 2015 at 20:38

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.