0

I have a discussion object which in it self has a ParentDiscussion and TopParentDiscussion:

 public class Discussion
    {
        [Key]
        public Guid ID { get; set; }
        public String Message { get; set; }
        public virtual Discussion ParentDiscussion { get; set; }
        public virtual Discussion TopParentDiscussion { get; set; }

    }

Both Parent and TopParent are optional. I wrote the following situation with the Fluent API and it works.

        modelBuilder.Entity<Discussion>().HasOptional<Discussion>(a => a.ParentDiscussion).WithOptionalDependent().Map(a => a.MapKey("TopParentId"));
        modelBuilder.Entity<Discussion>().HasOptional<Discussion>(a => a.TopParentDiscussion).WithOptionalDependent().Map(a => a.MapKey("ParentId"));

But how can I write this solution without the fluent api, so with data annotations.

I tried this:

        //Foreign Keys
        public Guid? ParentId { get; set; }
        public Guid? TopParentId { get; set; }

        //Relationships

        [ForeignKey("ParentId")]
        public virtual Discussion ParentDiscussion { get; set; }
        [ForeignKey("TopParentId")]
        public virtual Discussion TopParentDiscussion { get; set; }

But it gives me the following error:

Unable to determine the principal end of an association between the types 'Model.Discussion' and 'Model.Discussion'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Kevin Cloet
  • 2,956
  • 1
  • 19
  • 36

1 Answers1

0

You cannot map this with Data annotations because you don't expose foreign key property and reverse navigation property.

Correct mapping with fluent API is:

modelBuilder.Entity<Discussion>()
            .HasOptional<Discussion>(a => a.ParentDiscussion)
            .WithMany()
            .Map(a => a.MapKey("TopParentId"));
modelBuilder.Entity<Discussion>()
            .HasOptional<Discussion>(a => a.TopParentDiscussion)
            .WithMany()
            .Map(a => a.MapKey("ParentId"));

Because you want probably want a discussion to be parent of more then one other discussion.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Ok thanks, just wanted to know if it was possible or not. Just another quick question. When I want to find all discussions based on a ParentDiscussion I used to just do .Where(d => d.ParentId == SomeGuid) because I had a foreign key through Data Annotations. But with this solution I have to do the following .Where(d => d.ParentDiscussion.Id == SomeGuid), won't this cause a extra load of the actual ParentDiscussion? Or will EF translate ParentDiscussion.Id to the "ParentId" property? – Kevin Cloet Aug 16 '11 at 09:02