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?
I have the following code in my respository class:
MyDatabaseContext db = new MyDatabaseContext();
public void Insert(News news)
{
db.Newses.Add(news);
db.SaveChanges();
}
And then my insert store procedure will look like this:
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
Any articles/advice would be appreciated.
UPDATE 1:
With the designer I could return the new object or news ID, how would I do this here?
UPDATE 2
This is what I did:
public void Insert(News news)
{
int newsId = context.Database.SqlQuery<int>("News_Insert @Title, @Body, @Active",
new SqlParameter("Title", news.Title),
new SqlParameter("Body", news.Body),
new SqlParameter("Active", news.Active)
).FirstOrDefault();
context.SaveChanges();
}
I get an error here saying:
The specified cast from a materialized 'System.Decimal' type to the 'System.Int32' type is not valid.
My News class:
public class News
{
public int NewsId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public bool Active { get; set; }
}
I am using an existing database and my connection string looks like this:
<connectionStrings>
<add
name="MyDatabaseContext"
connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Here is my context class:
public class MyDatabaseContext : DbContext
{
public DbSet<News> Newses { get; set; }
}
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?