0

我有一个需要复杂关系的项目:

public enum InputFileTypes
{
    unknown = 0,
    ConfirmationFile = 1,
    PrestationFile = 2,
    EOCChoiceFile = 3,
    EOCReplaceFile = 4,
    CareStaffFile = 5,
    JobCreationFile = 6,
    NurseTitleFile = 7
};

public class InputFile
{
    [Key]
    public int Id { get; set; }
    public string Filename { get; set; }
    public InputFileTypes InputFileType { get; set; }
    public Guid ScraperUploadClassId { get; set; }
    public ScraperUploadClass ScraperUploadClass { get; set; }

    public DateTime FileDateTime
    {
        get
        {
            return File.GetCreationTime(Filename);
        }
    }
}

public class ScraperUploadClass
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid ID { get; set; }
    public Regions Region { get; set; }
    public virtual ICollection<InputFile> ConfirmationFiles { get; set; }
    public virtual ICollection<InputFile> PrestationFiles { get; set; }
    public InputFile EocChoiceFile { get; set; }
    public InputFile EocReplaceFile { get; set; }
    public InputFile CareStaffFile { get; set; }
    public InputFile JobCreationFile { get; set; }
    public InputFile NurseTitlesFile { get; set; }
}

modelBuilder.Entity<InputFile>()
    .HasIndex(c => new { c.InputFileType, c.ScraperUploadClassId });

问题是ModelBuilder:InputFile有一个组合的主键:inputfiletypeScraperUploadclassid.

Scraperclass需要对输入文件的多个关系:

  • 一对一的属性 EocCHoiceFile 其中 InputFile.InputFileType == InputFileTypes.EOCChoiceFile
  • 一对一的属性 EOCReplaceFile 其中 InputFile.InputFileType == InputFileTypes.EOCReplaceFile

...

  • 一对多的 Confirmationsfiles 列表,其中 InputFile.InputFileType == ConfirmationFile
  • 最后是 PrestationsFiles 列表的一对多,其中 InputFile.InputFileType == PrestationFile

谁能让我知道如何在DbContext.OnModelCreating方法中做到这一点?

我似乎没有用modelBuilder...来解决它。添加迁移时似乎总是会导致问题。

4

1 回答 1

0

找到答案 muyself,在 ScraperUploadClass 中仅使用一个虚拟列表,而不是为单独的类型创建 getter 函数

public class InputFile
    {
        [Key]
        public int Id { get; set; }
        public string Filename { get; set; }
        public InputFileTypes InputFileType { get; set; }
        public Guid ScraperUploadClassID { get; set; }
    }
    public class ScraperUploadClass
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public Guid ID { get; set; }
        public Regions Region { get; set; }
        public virtual ICollection<InputFile> InputFiles { get; set; }
    }

            modelBuilder.Entity<InputFile>()
                            .Property(c => c.InputFileType)
                            .HasConversion<string>();

            modelBuilder.Entity<InputFile>()
                .HasOne(d => d.ScraperUploadClass)
                .WithMany(p => p.InputFiles)
                .HasForeignKey(d => d.ScraperUploadClassID);

            modelBuilder.Entity<InputFile>()
             .HasIndex(t => new { t.ScraperUploadClassID, t.InputFileType, t.Filename })
             .IsUnique();
于 2021-09-17T06:13:48.763 回答