I have a table that self references to create a hierarchy.
CREATE TABLE [dbo].[Topics](
[ID] [uniqueidentifier] NOT NULL,
[ParentTopicID] [uniqueidentifier] NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Topics] PRIMARY KEY CLUSTERED
([ID] ASC)
WITH (
PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
ON [PRIMARY]
GO
ALTER TABLE [dbo].[Topics] WITH CHECK ADD CONSTRAINT [FK_Topics_Topics]
FOREIGN KEY([ParentTopicID]) REFERENCES [dbo].[Topics] ([ID])
For the “root” nodes, the ParentTopicID will be null, and children will point to appropriate TopicID.
This structure works in SQL but Entity Framework appears to be having problems with this. Even if I try a simple enumeration such as:
foreach(var t in container.Topics) {
Console.WriteLine(t);
}
I get an error:
The ‘ParentTopicID’ property on ‘Topic’ could not be set to a ‘null’
value. You must set this property to a non-null value of type ‘Guid’.
The second problem is to query this table to find the root nodes or children of a particular topic.
In SQL, it would be simple as Where ParentTopicID is null but since Guid is not null in .Net, Linq syntax complains and doesn’t find any matches.
yes, the problem here is your problem has NULL specified for the ParentTopicID but in EF Designer you probably have ParentTopicID set to nullable false. Change that first and we can go from there if it doesn’t fix it.
In the designer, select the class, select ParentTopicID, press F4 for properties.