[英]Entity Framework generated SQL queries
I have an 2 EF entity defined as: 我有一个2 EF实体定义为:
public class Event
{
public DateTime Created { get; set; }
public string Id { get; set; }
public bool Public { get; set; }
public EventType Type { get; set; }
public virtual ICollection<Note> Notes { get; set; }
}
public class Note
{
public string EventId { get; set; } // Link to parent event
public int Id { get; set; }
public string Text { get; set; }
public virtual Event Event { get; set; }
}
When accessing the Notes
collection in Event
, a SQL query is constructed in the form: 在Event
访问Notes
集合时,将以以下形式构造SQL查询:
exec sp_executesql N'SELECT
[Extent1].[Id] AS [Id],
[Extent1].[EventId] AS [EventId],
[Extent1].[Text] AS [Text]
FROM [dbo].[Notes] AS [Extent1]
WHERE [Extent1].[EventId] = @EntityKeyValue1',
N'@EntityKeyValue1 nvarchar(128)',
@EntityKeyValue1=N'N5427961'
This query, given the data size and indexing used required in excess of 3000 reads. 此查询,给定数据大小和索引使用超过3000读取所需。 This seemed a bit much given the tables have sufficient indexing. 鉴于表格具有足够的索引,这似乎有点多。 Query analyser had no suggestions to speed the query up. 查询分析器没有建议加快查询速度。
I then discovered if I changed the datatype being used in the SQL bind from nvarchar(128)
to varchar(33)
, which matches exactly the column type of EventId
in the DB table, the query now only needed 8 reads. 然后我发现如果我将SQL绑定中使用的数据类型从nvarchar(128)
更改为varchar(33)
,它与DB表中的EventId
的列类型完全匹配,则查询现在只需要8次读取。
Is this simply a case of me needing to use DataAnnotations to tell EF what the data types in SQL these fields are? 这只是我需要使用DataAnnotations来告诉EF这些字段中SQL的数据类型是什么情况吗? or is something else happening here? 或者是其他事情发生在这里?
I found the way to most easily get the desired effect was: 我发现最容易获得所需效果的方法是:
modelBuilder.Entity<Event>().Property(x => x.Id).IsUnicode(false).HasMaxLength(33);
The other suggested method using annotation did not work and resulted in nvarchar
still being used. 使用注释的其他建议方法不起作用,导致仍然使用nvarchar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.