Entity Framework将多个导航属性设置为同一个表

时间:2014-08-06 18:14:49

标签: entity-framework ef-code-first entity-framework-6

我对EF Code First有疑问,我无法找到解决方法:

我们说我有这两个POCO:

public class DocumentRequest
{
    // Database Id
    public Guid Id { get; set; }

    // Origin
    public Guid OriginDocumentId { get; set; }
    public Document OriginDocument { get; set; }
    // Target
    public Guid TargetDocumentId { get; set; }
    public Document TargetDocument { get; set; }
}

public class Document
{
    // Database Id
    public Guid Id { get; set; }

    public string DocumentMessage {get; set;}

    public Guid? FromDocumentRequestId { get; set; }
    public DocumentRequest FromRequest { get; set; }

    public ICollection<DocumentRequest> SentDocumentRequests {get; set;}
}

当我从一个Document创建DocumentRequest时,我创建了一个文档副本,然后创建了一个文档请求:

原始文档会将DocumentRequest添加到SentRequests导航属性

复制的文档将使FromDocumentRequestId指向DocumentRequestId

如何首先配置代码呢?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,这里是您需要的类和配置。

public class Document
{
    public Guid Id { get; set; }
    public string DocumentMessage { get; set; }
    public DocumentRequest FromRequest { get; set; }
    public ICollection<DocumentRequest> SentDocumentRequests { get; set; }
}
public class DocumentRequest
{
    // One Document to one DocumentRequest
    [Key, ForeignKey("Document")]
    public Guid DocumentId { get; set; }
    public Document Document { get; set; }
    public Guid OriginDocumentId { get; set; }
    public Document OriginDocument { get; set; }
}

的DbContext

public class AppContext : DbContext
{
    public DbSet<Document> Documents { get; set; }
    public DbSet<DocumentRequest> DocumentRequests { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // One Document to many SendDocumentRequests.
        modelBuilder.Entity<Document>()
            .HasMany(x => x.SentDocumentRequests)
            .WithRequired(x => x.OriginDocument)
            .HasForeignKey(x => x.OriginDocumentId)
            .WillCascadeOnDelete(false);
    }
}

结构

Structure

样本数据

  • 插入文档(Id = 1)
  • 复制文档(Id = 1),然后插入文档(Id = 2)
  • 插入了文档请求
    • DocumentId = 2
    • OriginDocumentId = 1
  • 再次复制文档(Id = 1),然后插入文档(Id = 3)
  • 插入了文档请求
    • DocumentId = 3
    • OriginDocumentId = 1

结果

<强>文档

Id
1
2
3

文件请求

DocumentId OriginDocumentId
    2            1
    3            1