I am getting SQL Exception:
String or binary data would be truncated
in SELECT. I read few questions with same title but they were all about inserting. I am SELECTING.
Code is following:
List<CategoryName> navigation = await db.Query<CategoryName>().FromSql(
$"WITH NestedCategories AS (
SELECT *
FROM Categories
WHERE Id IN (
{string.Join(",", products.Select(x =>
x.Categories.First().CategoryId).Distinct().Select(x => $"'{x}'"))}
)
UNION ALL
SELECT t.*
FROM Categories t
INNER JOIN NestedCategories c On c.ParentId = t.Id
)
SELECT DISTINCT c.Id, c.Name, c.ParentId
FROM NestedCategories c")
.AsNoTracking()
.ToListAsync();
If I generate string.Join to console and then put SQL command into query window in Management Studio I dont get any error. I get proper results. Issue is obviously in EF CORE that I am passing too many category Ids. Command is to get nesting categories based on Product-Category Id.
EDIT:
public class CategoryName
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
}
EDIT 2 - Solution
string inClause = string.Join(",", products.Select(x => x.Categories.First().CategoryId).Distinct().Select(x => $"'{x}'"));
List<CategoryName> navigation = new List<CategoryName>();
using (DbCommand command = db.Database.GetDbConnection().CreateCommand())
{
command.CommandText = $"WITH NestedCategories AS (SELECT * FROM Categories WHERE Id IN ({inClause}) UNION ALL SELECT t.* FROM Categories t INNER JOIN NestedCategories c On c.ParentId = t.Id) SELECT DISTINCT c.Id, c.Name, c.ParentId FROM NestedCategories c";
await db.Database.GetDbConnection().OpenAsync();
DbDataReader reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
navigation.Add(new CategoryName() { Id = reader.GetInt32(0), Name = reader.GetString(1), ParentId = await reader.IsDBNullAsync(2) ? null : await reader.GetFieldValueAsync<int?>(2) });
}
{string.Join(",", products.Select(x => x.Categories.First().CategoryId).Distinct())}be written as a SELECT in the SQL instead?string.JoinAdd something likeString.Join(",", list.Select(p => $"'{p}'")