0

Using EF Code First I have an model object that has multiple properties that are associated to a single model object:

public class Job 
{
    public int Id { get; set; }
    public int Company1Id { get; set; }
    public int Company2Id { get; set; } // References CompanyId
    public int Company3Id { get; set; } // References CompanyId
    ...

    public virtual Company Company1Info { get; set; }
    public virtual Company Company2Info { get; set; }
    public virtual Company Company3Info { get; set; }
 }

 public class Company
 { 
    public int CompanyId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
 }

Relationships in JobMap class

        this.HasRequired(t => t.Company1Info)
            .WithMany()
            .HasForeignKey(d => d.Company1Id);
        this.HasRequired(t => t .Company2Info)
            .WithMany()
            .HasForeignKey(d => d.Company2Id);
        this.HasRequired(t => t.Company3Info)
            .WithMany()
            .HasForeignKey(d => d.Company3Id);

Method in my repo to get data

 public Job GetById(int id)
    {
        return _dbContext.Set<Job>()
            .Include(t => t.Company1Info)
            .Include(t => t.Company2Info)
            .Include(t => t.Company3Info)
            .First(x => x.Id == id);
    }

When I run the application the Company2Info and Company3Info are null. I tried setting up a new DbSet instance for each company in the context but I got an Unsupported Exception.

Thanks!

Update: Here is an answer for the same problem but this is not working for me Entity Framework Code First - two Foreign Keys from same table

Community
  • 1
  • 1
Rich
  • 1,895
  • 3
  • 26
  • 35

1 Answers1

0

Solution:

The setup I have in my question and the solution in the link are correct. The object models I was creating instances of were null due to a non-existent key -- in other words, the Id for the company I was trying to reference did not exist.

The only change I made was to add the WillCascadeOnDelete method and set it to false as the default is true -- note I'm using the Fluent API in the JobMap class and not the Context ModelBuilder.

Relationships in JobMap class

    this.HasRequired(t => t.Company1Info)
        .WithMany()
        .HasForeignKey(d => d.Company1Id)
        .WillCascadeOnDelete(false);
    this.HasRequired(t => t .Company2Info)
        .WithMany()
        .HasForeignKey(d => d.Company2Id)
        .WillCascadeOnDelete(false);
    this.HasRequired(t => t.Company3Info)
        .WithMany()
        .HasForeignKey(d => d.Company3Id)
        .WillCascadeOnDelete(false);

HTH

Rich
  • 1,895
  • 3
  • 26
  • 35