如何获取和更改EF对象集元素?

时间:2012-09-03 06:45:26

标签: asp.net-mvc-3 entity-framework

我在mvc3中有数据库第一个应用程序。有评级表,整数类型有 ID Value 属性。总数是5。我想输入new Value,将它设置为Ratings的最后一个元素,并且每个元素的值都传递给元素的vaule之前。价值从上到下滑落。

public ActionResult UpdateRating( int newValue )
{

var rating0 = db.Ratings.ElementAt( 0 );
var rating1 = db.Ratings.ElementAt( 1 );
var rating2 = db.Ratings.ElementAt( 2 );
var rating3 = db.Ratings.ElementAt( 3 );
var rating4 = db.Ratings.ElementAt( 4 );

rating0.Value = rating1.Value;
rating1.Value = rating2.Value;
rating2.Value = rating3.Value;
rating3.Value = rating4.Value;
rating4.Value = newValue ;

db.Ratings.Attach( rating0 );
db.ObjectStateManager.ChangeObjectState( rating0 , EntityState.Modified );
db.Ratings.Attach( rating1 );
db.ObjectStateManager.ChangeObjectState( rating1 , EntityState.Modified );
db.Ratings.Attach( rating2 );
db.ObjectStateManager.ChangeObjectState( rating2 , EntityState.Modified );
db.Ratings.Attach( rating3 );
db.ObjectStateManager.ChangeObjectState( rating3 , EntityState.Modified );
db.Ratings.Attach( rating4 );
db.ObjectStateManager.ChangeObjectState( rating4 , EntityState.Modified );
db.SaveChanges();
...
}

我收到错误db.Ratings.ElementAt();线。我该怎么做这个操作?

1 个答案:

答案 0 :(得分:2)

替换为

public ActionResult UpdateRating( int newValue )
{

List<Rating> ratings = db.Ratings.OrderBy(r => r.id)
                        .ToList();

ratings[0].Value = ratings[1].Value;
ratings[1].Value = ratings[2].Value;
ratings[2].Value = ratings[3].Value;
ratings[3].Value = ratings[4].Value;
ratings[4].Value = newValue;

db.SaveChanges();
}