如果底层数据不反映实体主键,实体框架 4 将返回混乱的结果
我们有一个存储过程,其中有一个 select 语句:
select convert(int, c.ID) as ID,
convert(nvarchar(255), c.name) as name,
convert(varchar(32), a.state) as state
from customer c join address a on
c.addressid = a.ID
where c.name like @custNameSpec
在 T-SQL 窗口中执行时,它会生成两条记录:
ID Name State
1 Robert PA
2 Rob VA
当在 Entity Framework 4 中作为函数导入执行时,它返回两条记录,但第一条记录是重复的:
ID Name State
1 Robert PA
1 Robert PA
我们删除函数导入和导入的函数,重新创建它,等等。我们还添加了上面的那些 SQL Convert() 语句,以保证实体框架理解从服务器返回的数据类型。
我们可以做些什么来解决这个问题?是什么导致了这样的重复?
我们的测试包括:
var myresult3 = myUOW.DC.GetAdDir(todaysdate: null, store_nbr: 14,
adtype: null).ToList();
var myresult4 = DB.GetAdDir(todaysdate: null, store_nbr: 14,
adtype: null).ToList();
两者都返回相同的错误结果。 SQL 探查器显示此调用:
exec [dbo].[GetCust] @todaysdate=NULL,@custNameSpec='Rob',@adtype=NULL
编辑:
显然,业务规则发生了变化。从实体框架生成的 POCO 的主键设置不正确,因此它返回了正确数量的字段,但通过使所有重复项相同(基于 POCO 主键字段)来“删除”重复项
。 /code> 在其他远程相关问题中引用,可以解释为什么会发生这种情况。
We have a stored procedure that has a select statement in it:
select convert(int, c.ID) as ID,
convert(nvarchar(255), c.name) as name,
convert(varchar(32), a.state) as state
from customer c join address a on
c.addressid = a.ID
where c.name like @custNameSpec
This produces two records when executed in a T-SQL window:
ID Name State
1 Robert PA
2 Rob VA
When executed in Entity Framework 4 as a function import, it returns two records, but the first record is duplicated:
ID Name State
1 Robert PA
1 Robert PA
We deleted the function import and the imported function, recreated it, etc. We also added those SQL convert() statements above to guarantee Entity Framework understands the data types coming back from the server.
What could we do to fix it? What causes duplicates like that?
Our tests include:
var myresult3 = myUOW.DC.GetAdDir(todaysdate: null, store_nbr: 14,
adtype: null).ToList();
var myresult4 = DB.GetAdDir(todaysdate: null, store_nbr: 14,
adtype: null).ToList();
Both return the same incorrect result. The SQL profiler shows this call:
exec [dbo].[GetCust] @todaysdate=NULL,@custNameSpec='Rob',@adtype=NULL
EDIT:
Apparently, the business rules changed. The POCO generated from Entity Framework had a primary key improperly set, so it returned the correct quantity of fields, but "removed" duplicates by making all duplicates the same (based on the POCO primary key fields.)
There was MergeOption
referenced in other remotely related questions that may explain why this happens.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您对实体创建唯一限制(例如主键)并且数据中有重复项时,实体框架将为找到的每个重复项的所有字段重复第一个重复记录。
换句话说,如果您的基础数据未正确反映主键,实体框架将返回混乱的结果。
When you create a unique restriction on an Entity, like a primary key, and you have duplicates coming from the data, Entity Framework will repeat the first duplicate record for all fields for each duplicate found.
In other words, Entity Framework returns a mangled mess if your underlying data doesn't reflect the primary key correctly.