始终获取FK值0和导航属性为null

时间:2016-02-13 06:25:46

标签: c# entity-framework ef-code-first

我正在尝试创建foreign key relationship using Entity Framework Code first approach

我正在创建1-M relation b/w Vehicle and FileUpload(用户可以针对一辆车上传多张图片)。

问题:保存文件信息时,我总是得到FK value 0Vehicle navigation property null

请帮助了解我做错了什么?

以下是定义了FK关系的模型类。

车型

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

    public virtual ICollection<FileUpload> FileUploads { get; set; }

}

文件上传模型

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; }

}

我在控制器内的帖子方法

public HttpResponseMessage Post()
{
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 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();
}

1 个答案:

答案 0 :(得分:0)

data.VehicleId为0,因为数据是您创建的局部变量。

FileUpload data = new FileUpload();

这只是C#代码,Entity Framework Code First不知道什么是VehicleId,需要保存这些文件。

基本上,您需要在POST输入中或从创建Vehicle记录的片段中使用VehicleId。 (了解需要上传这些图像的车辆)

获得VehicleId后,将其设置在数据对象上。

FileUpload data = new FileUpload();
data.FileName = fileName;
data.VehicleId = vehicleId; // get this from POST input or the snippet that created the Vehicle record.. so vehicle.Id
db.FileUpload.Add(data);   

db.SaveChanges();