获取参数传递的对象的Id的问题

时间:2014-01-02 13:03:02

标签: c# .net asp.net-mvc entity-framework

我无法获取参数传递的对象的ID。

代码:

private void SetEntityState(TEntity entity, EntityState entityStated)
{
    var entry = this.Context.Entry(entity);

    if (entry.State == EntityState.Detached)
    {
        // The problem is here.
        TEntity attachedEntity = this.DbSet.Where(
            x => x.Id.Equals(entity.Id)
            ).FirstOrDefault();

        if (attachedEntity != null)
        {
            var attachedEntry = this.Context.Entry(attachedEntity);

            attachedEntry.CurrentValues.SetValues(entity);

            attachedEntry.State = entityStated;
        }
        else
        {
            entry.State = entityStated;
        }
    }
}

问题在于:

    TEntity attachedEntity = this.DbSet.Where(
        x => x.Id.Equals(entity.Id)
        ).FirstOrDefault();

'entity'的属性'Id'总是返回0但是在debbug中,我可以看到该值为3.

为什么会这样?

2 个答案:

答案 0 :(得分:0)

试试这个

 TEntity attachedEntity = this.DbSet.Where(x => x.Id == entity.Id).FirstOrDefault();

OR

Int32 entityId = entity.Id;
TEntity attachedEntity = this.DbSet.Where(x => x.Id == entityId).FirstOrDefault();

答案 1 :(得分:0)

也许你可以尝试(测试):

var entry = Context.Find(entity); 

而不是

var entry = this.Context.Entry(entity);