I've got two tables:
DocumentTypeId is a foreign key that refers to DocumentTypes table. Ie 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? Ie I'd like to have many documents with different document types.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.