实体框架流利的API映射简单的一对多关系流利、实体、框架、关系

2023-09-03 17:09:31 作者:失败者

我有两个表:

文档(ID,DocumentTypeId,标题,详细信息) DocumentTypes(ID,名称,描述)。

DocumentTypeId是指DocumentTypes表的外键。即所有文档都可以应    有分配给它们一个类型。

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

我有两个类:

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

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

和我有一个配置。

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'

如果我重新命名的FK列被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.

推荐答案

首先进行此更改。导航属性必须是虚拟

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

您不需要 HasKey 属性要求对标识字段,因为他们已经承担的约定。您的表必须有一列 DocumentId 在此配置。

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.