EntityFramework Code First self-referencing one to one (1:1) relationship mapping - Unable to determine the principal end

前提是你 提交于 2019-12-10 16:55:35

问题


I have this class:

public class Message
{
    public long Id { get; set; }

    public string Subject { get; set; }

    public string Message { get; set; }

    public virtual Message ParentMessage { get; set; }

    public virtual Message ChildMessage { get; set; }

    //...
}

Using EntityFramework Code First Add-Migration gives me the message: Unable to determine the principal end of an association between the types...

I can't use the [Required] attribute, because the first message in this thread will have no parent, the last message in the thread will have no child... how do I map this?

I tried:

        modelBuilder.Entity<Message>()
            .HasOptional(x => x.ParentMessage);

        modelBuilder.Entity<Message>()
            .HasOptional(x => x.ChildMessage);

but that did not work.


回答1:


I found something that looks like it could be it, if someone could verify that this is correct:

        modelBuilder.Entity<SecureMessage>()
            .HasOptional(x => x.ParentMessage)
            .WithOptionalDependent(x => x.ChildMessage);

So after some serious testing, this does indeed seem to be the solution.



来源:https://stackoverflow.com/questions/19825848/entityframework-code-first-self-referencing-one-to-one-11-relationship-mappin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!