There’s a way this works out that’s a self relationship 1 for 1, I don’t know what your real goal is to do so, maybe there are better ways, but, I ended up doing a minimal example and it works, because, in the relations of Entity Framework
there is always the list navigation and in that case there is no (list example).
Remarks:
In the example created by me it was like this:
namespace CslAppEFAutoOneToOne.Models
{
public class Document
{
public int DocumentId { get; set; }
public string Title { get; set; }
[ForeignKey("SourceDocument")]
public int? SourceDocumentId { get; set; }
public virtual Document SourceDocument { get; set; }
}
public class DatabaseContext : DbContext
{
public DatabaseContext()
: base("Server=.\\SqlExpress;Database=TestOneToOne;User Id=sa;Password=senha;")
{
Database.SetInitializer<DatabaseContext>(null);
}
public DbSet<Document> Document { get; set; }
}
}
Using:
using (DatabaseContext db = new DatabaseContext())
{
Document d1 = new Document()
{
Title = "Document 1"
};
Document d2 = new Document()
{
SourceDocumentId = d1.DocumentId,
SourceDocument = d1,
Title = "Document 2"
};
db.Document.Add(d1); //inserindo documento 1
db.Document.Add(d2); //inserindo documento 2 relacionado com 1
db.SaveChanges(); // salvando
var doc1 = db.Document.AsNoTracking()
.Include("SourceDocument")
.Where(x => x.DocumentId == 2)
.FirstOrDefault(); // filtro e seleção da relação.
}
In this example of how to use a record was inserted and the other related to the first and research seeking this relationship.
related: https://answall.com/questions/349636/auto-related-com-entity-framework-2-2/349745#349745
– novic
This answers your question? Relationship 1 to 1 with Entity Framework
– novic