Code inspection: Possible performance issues caused by unlimited string length
Entity Framework translates fields of entity classes to data types of the specific DBMS while creating the database schema. As the string
type in C# does not specify a maximum length by default, it assumes you want to store maximum length of data. For example, in SQL Server such data will be mapped to ntext
or varchar(MAX)
.
By default, SQL Server stores data in pages on disk where each row and its data can be 8060 bytes in size. Large object data types (LOB), such as varchar(max)
that is larger than 8060 bytes, are stored in a separate location in SQL Server. When a row is too large (or has many LOBs), SQL Server cannot read data in one go and has to look in several places to filter and return the result set for your query, resulting in additional I/O overhead.
To resolve the issue, you can set a maximum length for the reported property, for example, to 100 characters, using a Data Annotations or Fluent API attribute. This will map the property to nvarchar(100)
and prevent performance issues related to handling this property. Here is an example using Data Annotations:
Alternatively, you can use the HasMaxLength()
builder method in your database context model creation logic: