Always getting FK value 0 and navigation property null
<p>I am trying to create <code>foreign key relationship using Entity Framework Code first approach</code>. </p>

<p>I am creating <code>1-M relation b/w Vehicle and FileUpload</code> (user can upload multiple images against one vehicle).</p>

<p><strong>Problem:</strong> I always get <code>FK value 0</code> and <code>Vehicle navigation property null</code> when saving file information. </p>

<p><strong>Please help to understand what i am doing wrong?</strong></p>

<p>Following are model classes with FK relation defined.</p>

<p><strong>Vehicle model</strong></p>

<pre><code>public class Vehicle
{
    public Vehicle()
    {
        FileUploads = new List&lt;FileUpload&gt;();
    }
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection&lt;FileUpload&gt; FileUploads { get; set; }

}
</code></pre>

<p><strong>File Upload Model</strong></p>

<pre><code>public class FileUpload
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }


    [Required]
    public int Vehicle Id { get; set; }

    [ForeignKey("Vehicle Id")]
    public virtual Vehicle Vehicle { get; set; }

    [Required]
    [MaxLength(250)]
    [Display(Name = "File name")]
    public string FileName { get; set; }

    [Required]
    public string FileName{ get; set; }

}
</code></pre>

<p><strong>My post method inside controller</strong></p>

<pre><code>public HttpResponseMessage Post()
{
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count &gt; 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
            _saveToDB(postedFile.FileName);
        }
        return Request.CreateResponse(HttpStatusCode.Created);
    }
    return Request.CreateResponse(HttpStatusCode.BadRequest);
}

private void _saveToDB(string fileName)
{           
    FileUpload data = new FileUpload();
    data.FileName = fileName;
    db.FileUpload.Add(data);   // here data.VehicleId is always 0 and navigation property null. At this stage Vehicle record has been already created in database.
    db.SaveChanges();
}
</code></pre>