Entity Framework Fluent API for mapping a one-to-many simple relationship

I have two tables:

  • Documents (Id, DocumentTypeId, Title, Details)
  • DocumentTypes (Id, Name, Description).

DocumentTypeId is a foreign key that references a DocumentTypes table. That is, all documents can have the type assigned to them.

I have two classes:

public class Document { public string Id { get; set; } public string Title { get; set; } public DocumentType DocumentType { get; set; } } 

and

 public class DocumentType { public string Id { get; set; } public string Name { get; set; } public string Description { get; set; } } 

and ive got the configuration

 internal class DocumentsConfiguration : EntityTypeConfiguration<Document> { public DocumentsConfiguration() { ToTable("Documents"); HasKey(document => document.Id); Property(document => document.Id).HasColumnName("Id"); HasRequired(document => document.DocumentType);//???????? Property(document => document.Title).HasColumnName("Title").IsRequired(); } } 

And it does not work. I get this error message:

 Invalid column name 'DocumentType_Id' 

If I rename the fk column to DocumentType_Id, then Im will get this error message:

 Invalid column name 'DocumentTypeId' 

My question is how to establish a one-to-many relationship? That is, Id like to have many documents with different types of documents.

+4
source share
1 answer

Make this change first. Navigation properties must be virtual :

 public class Document { public string Id { get; set; } public string Title { get; set; } public virtual DocumentType DocumentType { get; set; } } 

Then change the configuration to the following:

 internal class DocumentsConfiguration : EntityTypeConfiguration<Document> { public DocumentsConfiguration() { HasRequired(document => document.DocumentType) .WithMany() .Map(e => e.MapKey("DocumentTypeId")); Property(document => document.Title).HasColumnName("Title").IsRequired(); ToTable("Documents"); } } 

You do not need HasKey or Property calls for the Id field, as they are already accepted by convention. In this configuration, the table must have a DocumentId column.

+6
source

Source: https://habr.com/ru/post/1434596/


All Articles