I am trying to use SqlHierarchyId in .net
In my controller I am using anonymous type to get value from database.
[HttpGet("{id}")]
public async Task<ActionResult<object>> GetDomain(int id)
{
object domain = from x in _context.Domains.Where(x => x.DomainId == id)
select new
{
Id = x.DomainId,
Name = x.DomainName,
Type = x.DomainTypeId,
Parent = x.Parentt,
Path = x.Level.ToString()
};
return domain;
}
Then I want to get the Path to convert to an SqlHierarchyId in order to apply different methods supported by .Net
I've try Reflection:
System.Type type = domain.GetType();
string strNode = (string) type.GetProperty("Path").GetValue(domain, null);
I have this error:
System.NullReferenceException: Object reference not set to an instance of an object.
When I debuged my code I found that strNode is null, but the domain contain all value I need when I test with Postman.
I try Dynamic:
dynamic dyn= domain;
string strNode= dyn.Path;
And I have this error:
Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<<>f__AnonymousType1>' does not contain a definition for 'Path
I also try several others propositions (Clone, define the anonymous type as a class...) found on similar question but no result.
Note: I am trying to use anonymous type because I can't get the value when direclty use my model. I have a casting error like.
Unable to cast object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.
But with anonymous I am able to get the values so I want to access those value and pass it to my model now.