Convert a string to a hierarchyid in C#
-
29-09-2019 - |
Question
I need to be able to convert a string to a hierarchyid in c#.net - I cannot use stored procedures.
When I pass in the path (string) the query fails as the path is stored like this '/' instead of /
Can I convert it to another type?
SqlCommand command = new SqlCommand("INSERT Structure (Path,Description,ParentID) " +
"VALUES(" + path + ".GetDescendant(" + lastChildPath +
", NULL) " +
",@description, @parentId", _connection);
-- BitKFu
I have added the and this is the sql query it produces:
CommandText = "INSERT Structure (Path,Description,ParentID) VALUES(CAST(/ AS hierarchyid).GetDescendant(NULL, NULL) ,@description, @parentId"
I get the following error: ex = {"Incorrect syntax near '/'."}
-- ck
This is what I am expecting
"INSERT Structure (Path,Description,ParentID) VALUES(/.GetDescendant(NULL, NULL) ,'Test', 1"
-- Paul Ruane
I have looked at this page already but it didnt really help, unless I overlooked something?
Thanks
Clare
Solution
I would try to cast it, if only the '' is wrong.
SqlCommand command = new SqlCommand("INSERT Structure (Path,Description,ParentID) " +
"VALUES(CAST('"+path+"' AS hierarchyid).GetDescendant(" + lastChildPath +
", NULL) " +
",@description, @parentId", _connection);
OTHER TIPS
I realize this is old, and has an answer, but wanted to add another option since I ran into this question trying to do the same thing.
You can convert from a string to a HierarchyId in C# by using the Microsoft.SqlServer.Types namespace and something like either:
SqlHierarchyId hierarchyIdRepresentation = (SqlHierarchyId)Convert.ChangeType(input, typeof(SqlHierarchyId))
or
SqlHierarchyId hierarchyIdRepresentation = SqlHierarchyId.Parse(input)
The .Parse()
method is called automatically anytime there is a conversion from a string and the .ToString()
method of the SqlHierarchyId
type overrides the standard string operator to return the canonical representation.