sql-server – 使用实体框架的存储过程4代码第一个CTP5

前端之家收集整理的这篇文章主要介绍了sql-server – 使用实体框架的存储过程4代码第一个CTP5前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Entity Framework 4 Code First CTP5和ASP.NET MVC 3.我想知道如何使用存储过程?

我的呼吁类中有以下代码

@H_404_4@MyDatabaseContext db = new MyDatabaseContext(); public void Insert(News news) { db.Newses.Add(news); db.SaveChanges(); }

然后我的插入存储过程将如下所示:

@H_404_4@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

任何文章/建议将不胜感激.

更新1:

与设计师可以返回新对象或新闻ID,我该怎么做?

更新2

这就是我所做的:

@H_404_4@public void Insert(News news) { int newsId = context.Database.sqlQuery<int>("News_Insert @Title,@Active",new sqlParameter("Title",news.Title),new sqlParameter("Body",news.Body),new sqlParameter("Active",news.Active) ).FirstOrDefault(); context.SaveChanges(); }

我在这里得到一个错误说:

从物化的“System.Decimal”类型到“System.Int32”类型的指定转换无效.

我的新闻课

@H_404_4@public class News { public int NewsId { get; set; } public string Title { get; set; } public string Body { get; set; } public bool Active { get; set; } }

我正在使用现有的数据库,我的连接字符串如下所示:

@H_404_4@<connectionStrings> <add name="MyDatabaseContext" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;" providerName="System.Data.sqlClient" /> </connectionStrings>

这是我的上下文类:

@H_404_4@public class MyDatabaseContext : DbContext { public DbSet<News> Newses { get; set; } }

我不知道我在这里做错什么?我的存储过程可能不正确吗?理想情况下,我想返回新的更新对象.有人可以请指教吗?

解决方法

没有对存储过程的直接映射支持(从EDMX已知).您可以使用db.Database.sqlCommand方法简单地调用您的过程而不是添加方法.尝试这个: @H_404_4@db.Database.sqlCommand("dbo.News_Insert @Title,@NewsStatusId",new sqlParameter("NewsStatusId",news.NewStatus.Id));

猜你在找的MsSQL相关文章