EF DbContext. How to avoid caching?

后端 未结 2 1218
清歌不尽
清歌不尽 2021-01-06 04:25

Spent a lot of time, but still cann\'t understand how to avoid caching in DbContext.

I attached below entity model of some easy case to demonstrate what I mean.

2条回答
  •  情深已故
    2021-01-06 04:52

    You can use the AsNoTracking method on your query.

    var res = (from b in ctx.Buildings.Where(x => x.ID == 1)
             select new
             {
                b,
                flats = from f in b.Flats
                        select new
                        {
                           f,
                           people = from p in f.People
                           where p.Archived == false
                           select p
                        }
             }).AsNoTracking().AsEnumerabe().Select(x => x.b).Single();
    

    I also want to note that your AsEnumerable is probably doing more harm than good. If you remove it, the Select(x => x.b) will be translated to SQL. As is, you are selecting everything, then throwing away everything but x.b in memory.

提交回复
热议问题