EF通过文件上传

时间:2015-11-26 11:15:57

标签: c# entity-framework

插入父记录时,我可以一次插入相关的子记录。但如果我的孩子记录是文件,那我怎么能一次插入和上传相关的子记录(文件)。文件将在不同的位置上传而不是数据库。

子文件类:

public class File
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string RelativePath { get; set; }
    public string MimeType { get; set; }
    public int Size { get; set; }
    public int QuestionId { get; set; }
    public string ApplicationUserId { get; set; }
}

父项目插入代码:

public ActionResult Create(QuestionCreateViewModel viewModel)
{
    var question = new Question
    {
        Text = viewModel.Text,
        QuestionType = viewModel.QuestionType,
        Answer = viewModel.Answer,
        Notes = viewModel.Notes,
        CategoryId = viewModel.CategoryId,
        Files = viewModel.Files // Also need to Upload
    };

    _questionRepository.Insert(question);
    _questionRepository.Save();

    return Json(null);
}

现在我在插入父数据和子数据时将文件上传代码放到上传文件中。

1 个答案:

答案 0 :(得分:3)

我这样解决它:我使用了一个名为ManageFiles(Request.Files)的额外函数,它上传所有文件然后返回上传文件列表。因此,当父记录插入时,它还会上传它的子文件并一次性插入文件记录。

public ActionResult Create(QuestionCreateViewModel viewModel)
{
    var question = new Question
    {
        Text = viewModel.Text,
        QuestionType = viewModel.QuestionType,
        Answer = viewModel.Answer,
        Notes = viewModel.Notes,
        CategoryId = viewModel.CategoryId,
        Files = ManageFiles(Request.Files)
    };

    _questionRepository.Insert(question);
    _questionRepository.Save();

    return Json(null);
}

private ICollection<File> ManageFiles(HttpFileCollectionBase fileCollection)
{
    var files = new List<File>();

    for (var index = 0; index < fileCollection.Count; index++)
    {
        if (fileCollection[index] == null || fileCollection[index].ContentLength <= 0)
        {
            continue;
        }

        if (UploadFile(Request.Files[index]))
        {
            var file = new File
            {
                Name = uploaded.FileName,
                RelativePath = uploaded.FilePath + uploaded.FileName,
                MimeType = uploaded.FileBase.ContentType,
                Size = uploaded.FileBase.ContentLength
            };

            files.Add(file);
        }
    }

    return files;
}