title: Using stored procedures with Entity Framework 4 Code First CTP5
body: <p>I am using Entity Framework 4 Code First CTP5 and ASP.NET MVC 3.  I would like to know how do I make use of stored procedures?</p>
  
  <p>I have the following code in my respository class:</p>
  
  <pre><code>MyDatabaseContext db = new MyDatabaseContext();
  
  public void Insert(News news)
  {
     db.Newses.Add(news);
     db.SaveChanges();
  }
  </code></pre>
  
  <p>And then my insert store procedure will look like this:</p>
  
  <pre><code>ALTER PROCEDURE [dbo].[News_Insert]
  (
     @Title VARCHAR(100),
     @Body VARCHAR(MAX),
     @NewsStatusId INT
  )
  
  AS
  
  BEGIN
  
     INSERT INTO
        News
        (
           Title,
           Body,
           NewsStatusId
        )
        VALUES
        (
           @Title,
           @Body,
           @NewsStatusId
        );
  
    SELECT SCOPE_IDENTITY();
  
  END
  </code></pre>
  
  <p>Any articles/advice would be appreciated.</p>
  
  <p><strong>UPDATE 1:</strong></p>
  
  <p>With the designer I could return the new object or news ID, how would I do this here?</p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>This is what I did:</p>
  
  <pre><code>public void Insert(News news)
  {
     int newsId = context.Database.SqlQuery&lt;int&gt;("News_Insert @Title, @Body, @Active",
        new SqlParameter("Title", news.Title),
        new SqlParameter("Body", news.Body),
        new SqlParameter("Active", news.Active)
     ).FirstOrDefault();
  
     context.SaveChanges();
  }
  </code></pre>
  
  <p>I get an error here saying:</p>
  
  <p><strong>The specified cast from a materialized 'System.Decimal' type to the 'System.Int32' type is not valid.</strong></p>
  
  <p>My News class:</p>
  
  <pre><code>public class News
  {
     public int NewsId { get; set; }
     public string Title { get; set; }
     public string Body { get; set; }
     public bool Active { get; set; }
  }
  </code></pre>
  
  <p>I am using an existing database and my connection string looks like this:</p>
  
  <pre><code>&lt;connectionStrings&gt;
     &lt;add
        name="MyDatabaseContext"
        connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"
        providerName="System.Data.SqlClient" /&gt;
  &lt;/connectionStrings&gt;
  </code></pre>
  
  <p>Here is my context class:</p>
  
  <pre><code>public class MyDatabaseContext : DbContext
  {
     public DbSet&lt;News&gt; Newses { get; set; }
  }
  </code></pre>
  
  <p>I'm not sure what I am doing wrong here?  Is my stored procedure maybe incorrect?  Ideally I would like to return the new updated object.  Can someone please advise?</p>