Я работаю над своим первым проектом с использованием ASP MVC3.Мое приложение сначала кодирует, используя Entity Framework 4.1 и SQL-сервер CE.
Приложение представляет собой библиотеку документов.Основная модель - это Document, представляющий собой путь к pdf-файлу и кучу метаданных.
У меня есть функция «замена» в моем контроллере, которая берет одну запись Document, перемещает файл в местоположение архива иобновляет базу данных информацией о замене.Я пытаюсь сохранить список строк с документом, которые представляют пути к файлам для более старых версий того же документа.
Независимо от того, что я не могу получить этот список, называемый ArchivedFilePaths, для чего-либо, кроме "null".
Модель:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace DocLibrary.Models
{
public class Document
{
public int DocumentId { get; set; }
public int CategoryId { get; set; }
public string DocumentCode { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string FileUrl { get; set; }
public int FileSize { get; set; }
public string FileSizeString { get; set; }
public int Pages { get; set; }
public string Creator { get; set; }
public int Revision { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime LastModifiedDate { get; set; }
public virtual Category Category { get; set; }
public List<String> ArchivedFilePaths { get; set; }
public SoftwareVersion SoftwareVersion { get; set; }
}
Контроллер:
public ActionResult Replace(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
int id = Int32.Parse(Request["DocumentId"]);
Document doc = docsDB.Documents.Find(id);
//move the current version to the ~/Archive folder
string current_path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(doc.FileUrl));
string archiveFileName = Path.GetFileNameWithoutExtension(doc.FileUrl) + "-" + doc.Revision.ToString() + ".pdf";
string destination_path = Path.Combine(Server.MapPath("~/Archive"), archiveFileName);
System.IO.File.Move(current_path, destination_path);
if (doc.ArchivedFilePaths == null)
{
doc.ArchivedFilePaths = new List<String>();
}
doc.ArchivedFilePaths.Add(destination_path);
//there are a bunch of statements that update the title, number of pages, etc. here, all of these work fine
try
{
docsDB.Entry(doc).State = EntityState.Modified;
docsDB.Logs.Add(new Log { LogDate = DateTime.Now, LogText = "Document replaced with a new version: " + doc.Title, });
docsDB.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
//if a file was not selected;
return RedirectToAction("Index");
}
Представление «Индекс» отображает все файлы и их свойства, включая ArchivedFilePaths.После замены документа новым файлом все элементы в модели документа обновляются должным образом, за исключением ArchivedFilePaths.
Если я проверю список в VisualStudio, он не будет нулевым после оператора doc.ArchivedFilePaths.Add
.Поэтому я не верю, что список когда-либо сохраняется в базе данных, и я подозреваю, что с моей моделью что-то не так.Если я изменю ее на одну строку, я смогу ее обновить.
У кого-нибудь есть понимание?Благодаря.