问题
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