The operation cannot be completed because the DbContext has been disposed error

后端 未结 8 1998
情歌与酒
情歌与酒 2020-11-29 09:22

I\'m new to EF and I\'m trying to use an extension method which converts from my Database type User to my info class UserInfo.
I\'m using data

8条回答
  •  遥遥无期
    2020-11-29 09:42

    This can be as simple as adding ToList() in your repository. For example:

    public IEnumerable GetMyObjectsForId(string id)
    {
        using (var ctxt = new RcContext())
        {
            // causes an error
            return ctxt.MyObjects.Where(x => x.MyObjects.Id == id);
        }
    }
    

    Will yield the Db Context disposed error in the calling class but this can be resolved by explicitly exercising the enumeration by adding ToList() on the LINQ operation:

    public IEnumerable GetMyObjectsForId(string id)
    {
        using (var ctxt = new RcContext())
        {
            return ctxt.MyObjects.Where(x => x.MyObjects.Id == id).ToList();
        }
    }
    

提交回复
热议问题