Entity Framework Fluent API to map simple one-to-many relation

.net c# entity-framework

Question

I’ve got two tables:

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

DocumentTypeId is a foreign key that refers to DocumentTypes table. I.e. all documents can should have a type assigned to them.

I’ve got 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 I’ve got a 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 this is not working. I’m getting this error message:

Invalid column name 'DocumentType_Id'

If I rename the fk column to be DocumentType_Id then I’m getting this error message:

Invalid column name 'DocumentTypeId'

My question is how do I set such one-to-many relation? I.e. I’d like to have many documents with different document types.

1
4
4/1/2013 11:14:42 PM

Accepted Answer

First make this change. Navigation properties have to be virtual:

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

Then change your configuration to this:

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 don't need the HasKey or Property calls for the Id field because they are already assumed by convention. Your table must have a column DocumentId in this configuration.

6
9/17/2012 12:44:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow