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

.net c# entity-framework

Question

I have two tables.

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

A foreign key that points to the DocumentTypes database is DocumentTypeId. In other words, every document should have a type assigned to it.

I'm enrolled in two courses.

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; }
}

moreover, I have 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();
    }
}

Further, this is ineffective. I'm experiencing the following error:

Invalid column name 'DocumentType_Id'

I receive the following error warning if I change the fk column to DocumentType Id:

Invalid column name 'DocumentTypeId'

How can I build up such a one-to-many relation is my query. For example, I would want to have a variety of document kinds.

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

Accepted Answer

First, make this adjustment. Navigational features mustvirtual :

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

Change your setup to this after that:

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 theHasKey or Property requires theId since by convention they are already taken into field. The column in your table must exist.DocumentId in this arrangement.

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