HierarchyID in Entity Framework not working
Asked Answered
N

2

12

We are using WCF Data Service based on an Entity Framework model for our application.

In this we need to add the table with a column of type HierarchyId. When I add that table to the EDMX file, the HierarchId column is not appearing in the class file.

What should I do to make use of HierarchyID? I read that Entity Framework is not supporting HierarchyID, so how can I achieve this?

Nabob answered 30/11, 2010 at 16:34 Comment(3)
Your problem is with EF, not WCF. The problem is that EF can't represent hierarchyid columns.Overtrump
I used this little bit of code to make working with HierarchyID strings a bit easier... #3348360Shiller
@EBarr, Your implementation looks good, my requirement was just use the existing HierarchyID as it is. The only thing i did was, used computed Column since EF don't support. By the use of computed column, its doing its job great.Nabob
H
24

You can always convert a HierarchyId to its string representation - something like /1/3/4/1 - and send that string across the WCF data service.

Update: if you add this computed, persisted column to your SQL Server table, that new column should definitely show up in your EF model and you should be able to use this to send it back over WCF and WCF Data Services:

ALTER TABLE dbo.YourTable
ADD HierarchyString AS (your hierarchyID field).ToString() PERSISTED

Update #2: read the docs! You can parse back a string like /1/3/4/1 into a HierarchyId type - either use the HierarchyId::Parse(string) or the usual CAST(string as HierarchyId) methods to do so.

Horick answered 30/11, 2010 at 17:28 Comment(2)
As i told early, while adding the table to the EDMX file, the hierarchyId field is not appearing. So i have to have method in svc file and insert using "insert into ... " query?Nabob
OK, This can be used as getter, how about setter? i tried the setter kind of stuff. If setter is possible, everything can be done in simpler way. By using this i'm able to get the data. Thanks marc_s.Nabob
S
10

If you use the computed column just keep in mind that you will also need the DatabaseGenerated data annotation on your property like this:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string HierarchyString { get; set; }

Check this article out for more info: Entity Framework Code First Computed Properties

Scrope answered 2/8, 2011 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.