One-To-One relationship with the same Entity Framework table

Asked

Viewed 108 times

0

I don’t know how to perform the relationship one to one on the same table on Entity Framework.

Example:

namespace cruddef.Models
{
    public class Document
    {
        public int DocumentID { get; set; }
        public int SourceDocumentID { get; set; }
    }  
}

What I need to do, I need to relate the table Document with itself, using the key SourceDocumentID with the DocumentID, This in the configuration document of EF and I need this to work:

public virtual Document DOCUMENT_SOURCE { get; set; }

1 answer

0

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:

  • for this to work in the item that will be the foreign key of the table must be of the type null.
  • configure this foreign key field with [ForeignKey("DOCUMENT_SOURCE")] of namespace System.ComponentModel.DataAnnotations.Schema right now is configuring self - relationship.
  • minimal example:

    namespace cruddef.Models
    {
        public class Document
        {
            public int DocumentID { get; set; }
    
            [ForeignKey("DOCUMENT_SOURCE")]
            public int? SourceDocumentID { get; set; }
            public virtual Document DOCUMENT_SOURCE { get; set; }
        }  
    }
    

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.