eugenekgn
eugenekgn

Reputation: 1722

Entity Framework loading foreign keys with HasOptional

Is it possible to load ProjectManager by ForeignKey while using it

this.HasOptional(t => t.ProjectManager)
            .WithMany()
            .WillCascadeOnDelete(false)

I tried doing the following, and ProjectManager still returns as null

var entities = _context.EodRecords
            .Include(r =>r.ProjectManager)
            .Include(r => r.RecordLanguages)
            .Include(r => r.Department);

Upvotes: 2

Views: 3526

Answers (1)

James
James

Reputation: 82096

You don't appear to have specified the foreign key

this.HasOptional(t => t.ProjectManager)
    .WithMany()
    .HasForeignKey(t => t.ProjectManagerId)
    .WillCascadeOnDelete(false);

Based on your error

Contexts.Record_ProjectManager: : Multiplicity conflicts with the referential constraint in Role 'Record_ProjectManager_Target' in relationship 'Record_ProjectManager'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

Make sure your FK is nullable

public virtual int? ProjectManagerId { get; set; }

Upvotes: 3

Related Questions