存根更新实体框架中的实体

时间:2014-04-12 18:15:57

标签: asp.net-mvc entity-framework entity-framework-5 entity-framework-6

我希望使用存根更新方式更新Entity Framework 6中的实体属性(Count),实际上我想要加一个Count属性值而不使用查询数据库。我怎么能这样做?

      //...
      var stub = new entity {Id = id};
      _articles.Attach(stub);

      stub.Count++; // Count always is 1! How i can do this without fetch/query database?
      context.SaveChanges();
      //...

1 个答案:

答案 0 :(得分:0)

我唯一知道的方法是使用存储过程。

create proc sp_UpdateCount @Id int
as
update [dbo].[EntityTable] set [Count] = [Count] + 1
where [Id] = @Id 

然后在代码中运行它

SqlParameter paramId = new SqlParameter("@Id", id);
context.Database.ExecuteSqlCommand("sp_UpdateCount @Id", paramId);

请注意,这将立即执行此过程,您不必为此调用SaveChanges。如果要在事务中执行其他更改的过程,请确保使用TransactionScope显式创建一个。

希望它有所帮助!