loyalflow
loyalflow

Reputation: 14919

How to return a single result set using EF 6 and codefirst?

I am currently returning a collection and then grabbing the first item, but there must be a way to only return a single result set.

Here is what I have now:

ICollection<SomeTestDTO> results =
   this.Context.Database.SqlQuery<SomeTestDTO>(
     "[myStoredProcedure1] @p1, @p2", p1, p2).Cast<SomeTestDTO>().ToList();

How can I convert this to return a single instance of SomeTestDTO?

Also, if my codefirst class SomeTestDTO doesn't map exactly with the columns returned, should I use the [Column("abc123")] attributes like in my regular models?

Upvotes: 1

Views: 272

Answers (2)

Mister Epic
Mister Epic

Reputation: 16743

This is a bit of an aside, but it might be more elegant to import your stored procedure as a function into your EF context.

Open the model browser, and navigate to myStoredProcedure1. Right-click and select Add Function Import. This will open a wizard where you can specify the mapping between the stored procedure and your EF entity.

Once that's done, the syntax to use the stored procedure from your EF context is pretty simple:

  SomeTestDTO dto = context.myStoredProcedure1(p1, p2).SingleOrDefault();

Ref: http://msdn.microsoft.com/en-us/data/gg699321.aspx

Upvotes: 1

user1783143
user1783143

Reputation:

 this.Context.Database.SqlQuery<SomeTestDTO>(
 "[myStoredProcedure1] @p1, @p2", p1, p2).Cast<SomeTestDTO>().FirstOrDefault ();

or you can also use SingleOrDefault() but beware this will throw an exception if more than one result.

Upvotes: 2

Related Questions