开发者

2 properties pointing to the same class in EF code first

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜