0

Trying to store a composite key table which is keyed for both fields to the table it defines dependencies for.

Example case Import files: 1..10 Dependencies 1: 2,3; 2: 4,5; 4:10

Intent is to use this key-only table for code to do code first strongly typed definitions while also being light weight, and it seemed like the most straight forward way to do it before running into problems.

Current code:

    public class ImportFileDependency
    {
        [Key]
        [ForeignKey("ImportFile")]
        public int ImportFileId { get; set; }
        [ForeignKey("Id")]
        public ImportFile ImportFile {get; set;}


        [Key]
        [ForeignKey("ImportFile")]
        public int ImportFileDependencyId { get; set; }
        [ForeignKey("Id")]
        public ICollection<ImportFile> ImportFileDependencies { get; set; }
    }

    public class ImportFile
    {
        [Key]
        public int Id {get; set;}
        public string Name { get; set; }
        public string WorkbookTab { get; set; }
        public string File { get; set; }
        public ICollection<ImportFileDependency> Dependencies { get; set; }       
    }
...

            modelBuilder
                .Entity<ImportFileDependency>(e =>{
                    e.HasKey(ifd => new { ifd.ImportFileId, ifd.ImportFileDependencyId });
                    e.HasOne(ifd => ifd.ImportFile)
                        .WithMany(i => i.Dependencies);
                });

            modelBuilder
                .Entity<ImportFile>()
                .HasMany(i => i.Dependencies)
                .WithOne()
                .HasForeignKey(z => z.ImportFileId);
...

After multiple revisions of following the responses of the add-migration exception response, currently on:

There are multiple properties pointing to navigation 'ImportFile' in entity type 'ImportFileDependency'. To define composite foreign key using data annotations, use ForeignKeyAttribute on navigation.

which did not update from the most recent iteration.

I seem to have recursed into a deadend so looking for guidance

Captain Prinny
  • 459
  • 8
  • 23

1 Answers1

0

Given the time you've asked it, you probably found the answer yourself or gave up on it, but if someone else struggles with this error, this solved my issue: Entity Framework Code First - two Foreign Keys from same table

You have to define the relationship using fluent API.

Alef Duarte
  • 112
  • 1
  • 3
  • 13