LINQ select on a SQL View gets wrong answer

后端 未结 7 1359
猫巷女王i
猫巷女王i 2021-01-05 02:07

I have a SQL View that produces a response with 8 columns. Its a rather complicated so I won\'t list it here and it won\'t add much to the issue I\'m trying to understand.

7条回答
  •  轮回少年
    2021-01-05 02:55

    If the key that the entity framework chooses for the view is not unique, then results may not be returned correctly. For some views, a proper key (with all non-null columns) cannot be defined and provides no benefit to consuming the view.

    For these cases, consider manually defining the key using the EF Edmx interface as:

     1) Any existing non-null field or 
    
     2) A separately added column "key" such as:
    
         select 1 as EfKey -- Must use with AsNoTracking()
    

    Both approaches require the use of "AsNoTracking()" for each query (link).

    Using AsNoTracking() signals EF to bypass its record caching mechanism which is based on the key. Without AsNoTracking(), the results may be corrupted containing duplicate rows.

    An advantage of using (2) is that if AsNoTracking() is forgotten, then the results should be so bad that it is easily noticed.

    Avoid using any variant of row_number() as it often prevents efficient use of predicates within the SQL Engine. This can be verified by viewing the SQL Actual Plan with a predicate. (Apologies as it was the advice I had originally posted.)

       -- Avoid!
       select row_number() over (order by (select null)) as RowId,
              ...
    

    Hopefully the EF Team would consider having a option for views that allows disabling of Key requirement and automatic use of AsNoTracking() with each query.

提交回复
热议问题