且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

EntityFramework从SQL Server视图返回损坏/转换的数据

更新时间:2023-01-30 12:51:41

The cause of this strange behavior is already mention here or here. It seems that the EF internally cache the entire table, but EF selected wrong unique key and in consequence the the data in the row get replaced by data from different rows.

This SELECT is made from a view. This view has no primary key. EF decided to be too clever and choose the primary key on his own for caching purposes. But EF has chosen wrong key, I mean EF has chosen only 2 columns of four.

To fix it, go to the EDMX model, right click to the header of problematic View and choose "Show in model browser". Then check, that all columns has the property EntityKey set to true. That is all.

Because of this and other "features" of EF I am bit disappointed by EF. This code worked fine in LinqToSQL wihtout any magic. And it is not the first query when LinqToSql behave correctly and EF behavior is at least problematic or crashing runtime. I am afraid Microsoft is breaking "get what you expect pattern" here. When I query the entire view, I just expect simple code which get the data from the view.