2016-05-27 4 views
0

Что я пытаюсь сделать, это загрузить файл xml в мое приложение mvc, но независимо от того, как я его реализую, он всегда возвращает число ноль, я знаю, как это сделать im is not just best сохраняя загрузчик xml в классе конфигурации, который создается методом миграции, но он работал, и теперь он прекратил цитирование «только часть адреса может быть достигнута». Мне было интересно, есть ли способ исправить это?Xml в Asp.net MVC

Catalog.cs

public class CatalogController : BaseController 
{  
    // GET: Catalog 
    public ActionResult Index() 
    { 
     List<Category> Categories = DbContext.Categories.OrderBy(c => c.Name).ToList(); 
     int NumberofBooks = DbContext.Books.Count(); 
     List<PublicationThumbnail> bookItems = GetBookThumbNails(5); 

     HomeViewModel homeViewModel = new HomeViewModel(Categories, NumberofBooks, bookItems); 
     return View(homeViewModel); 
    } 

    public ActionResult Search(string c = null, string t = null) 
    { 
     string searchMessage = (t == null ? "Publications" : t); 
     if (c != null) 
     { 
      searchMessage += " in " + c; 
     } 
     List<PublicationThumbnail> imageThumbNail = 
      FilterPublications(c, t).Select(p => new PublicationThumbnail(p)).ToList(); 
     SearchViewModel searchViewModel = new SearchViewModel() 
     { 
      FilterMessage = searchMessage, 
      Thumbnails = imageThumbNail, 
      ResultsCount = imageThumbNail.Count 
     }; 
     return View(searchViewModel); 
    } 

    public ActionResult View(int id) 
    { 
     Publication foundPublications = DbContext.Publications.Find(id); 
     if (foundPublications != null) 
     { 
      Account currentUser = null; 
      if (User.Identity.IsAuthenticated) 
      { 
       currentUser = AccountManager.GetCurrentUser(User); 
      } 
      return View(new PublicationViewModel(foundPublications, currentUser)); 
     } 
     return HttpNotFound(); 
    } 

    [Authorize] 
    public ActionResult Download(int id) 
    { 
     Account account = AccountManager.GetCurrentUser(User); 
     if (account != null && (account.Subscribed() || account.PurchasedItem(id))) 
     { 
      Publication publication = DbContext.Publications.FirstOrDefault(p => p.Id == id); 
      return View(publication); 
     } 
     return HttpNotFound(); 
    } 

    private List<Publication> FilterPublications(string category, string publicationType) 
    { 
     List<Publication> results = new List<Publication>(); 
     if (publicationType != null) 
     { 
      if (publicationType.ToLower() == "books") 
      { 
       results.AddRange(DbContext.Books); 
      } 
     } 
     else 
     { 
      results.AddRange(DbContext.Publications); 
     } 

     if (category != null) 
     { 
      Category categoryMatch = DbContext.Categories.FirstOrDefault(c => c.Name == category); 
      if (categoryMatch != null) 
      { 
       results = results.Where(p => p.Categories.Contains(categoryMatch)).ToList(); 
      } 
     } 
     return results; 
    } 

    private List<PublicationThumbnail> GetBookThumbNails(int count) 
    { 
     List<Book> books = DbContext.Books.Take(Math.Min(count, DbContext.Books.Count())).ToList(); 
     return books.Select(j => new PublicationThumbnail(j)).ToList(); 
    } 
} 

Books.xml

<?xml version="1.0" encoding="utf-8" ?> 
<Books> 
    <Book> 
     <Title>The Rabbit Who Wants to Fall Asleep: A New Way of Getting Children to Sleep</Title> 
     <Description>The groundbreaking No. 1 bestseller is sure to turn nightly bedtime battles into a loving and special end-of-day ritual. This child-tested, parent-approved story uses an innovative technique that brings a calm end to any child's day.</Description> 
     <Authors>Carl-Johan Forssén Ehrlin</Authors> 
     <Chapters>4</Chapters> 
     <Edition>1</Edition> 
     <PublicationDate>2016-05-21T10:50:23.5602265-04:00</PublicationDate> 
     <PublicationFormat>PDF</PublicationFormat> 
     <FileLocation>App_Data/Publications</FileLocation> 
     <ISBN>978-3-319-30715-2</ISBN> 
     <Categories> 
      <Category> 
       <Name>Other</Name> 
      </Category> 
     </Categories> 
     <ThumbnailLocation>TheRabbit.jpg</ThumbnailLocation> 
     <Price>4.00</Price> 
    </Book> 
</Books> 

класс конфигурации

internal sealed class Configuration : DbMigrationsConfiguration<HullUniversityPress.DataAccessLayer.HullPressContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = false; 
    } 

    protected override void Seed(HullPressContext context) 
    { 
     if (context.Books.Count() == 0) 
     { 
      SeedPublicationCategories(context); 
      SeedBooks(context); 
      SeedAccounts(context); 
      SeedSubscriptions(context); 
     } 
    } 

    private XDocument LoadXmlDoc(string fileName) 
    { 
     XDocument xmlDoc = XDocument.Load("HullUniversityPress/App_Data/" + fileName); 
     return xmlDoc; 
    } 

    private void SeedBooks(HullPressContext context) 
    { 
     XDocument xmlDoc = LoadXmlDoc("Books.xml"); 
     foreach (XElement j in xmlDoc.Root.Elements("Book")) 
     { 
      Book newBook = new Book() 
      { 
       Title = j.Element("Title").Value, 
       Description = j.Element("Description").Value, 
       ISBN = j.Element("ISBN").Value, 
       FileLocation = j.Element("FileLocation").Value, 
       ThumbnailLocation = j.Element("ThumbnailLocation").Value, 
       Chapters = int.Parse(j.Element("Chapters").Value), 
       Edition = int.Parse(j.Element("Edition").Value), 
       Langauge = (Language)Enum.Parse(typeof(Language), j.Element("Language").Value), 
       Authors = j.Element("Authors").Value, 
       Price = decimal.Parse(j.Element("Price").Value), 
       PublicationFormat = (PublicationFormat)Enum.Parse(typeof(PublicationFormat), j.Element("PublicationFormat").Value), 
       PublicationDate = DateTime.Parse(j.Element("PublicationDate").Value) 
      }; 
      ParseCategories(newBook, context, j.Element("Categories")); 
      context.Books.Add(newBook); 
     } 
    } 

    private void ParseCategories(Publication publication, HullPressContext context, XElement categoryRoot) 
    { 
     publication.Categories = new List<Category>(); 
     foreach (XElement category in categoryRoot.Elements("Category")) 
     { 
      string categoryName = category.Element("Name").Value; 
      Category match = context.Categories.Local.FirstOrDefault(c => c.Name == categoryName); 
      if (match != null) 
      { 
       publication.Categories.Add(match); 
       match.Publications.Add(publication); 
      } 
      else throw new Exception("Unidentified category: " + category.Element("Name").Value + ", Categories: " + context.Categories.Local.Count()); 
     } 
    } 

    private void SeedPublicationCategories(HullPressContext context) 
    { 
     context.Categories.AddOrUpdate(
      new Category("Other") 
      ); 
    } 

    private void SeedAccounts(HullPressContext context) 
    { 
     context.Accounts.AddOrUpdate(
      new Account("[email protected]", "Hello12345") 
      ); 
    } 

    private void SeedSubscriptions(HullPressContext context) 
    { 
     Account account = context.Accounts.Local.FirstOrDefault(u => u.Email == "[email protected]"); 
     Book bookSub = context.Books.Local.FirstOrDefault(); 
     if (account != null && bookSub != null) 
     { 
      context.Purchases.Add(new Purchase() 
      { 
       Account = account, 
       Publication = bookSub, 
       Format = PublicationFormat.PDF 
      }); 
     } 
    } 
} 

Любой вид помощи/указал в правой прямой будет значительно получил.

+3

Большая часть этого с ode не имеет никакого отношения к вашему вопросу - [Как создать минимальный, полный и проверяемый пример] (http://stackoverflow.com/help/mcve) –

+0

Вы добавляете элементы в контекст, но вы, кажется, не вызываете .Сохранить изменения() – Pawel

ответ

0

Я не уверен, как этот код никогда не работал, я воссоздал проблему с моей стороны и изменил эту строку:

XDocument xmlDoc = XDocument.Load("HullUniversityPress/App_Data/" + fileName); 

к этому:

XDocument xmlDoc = XDocument.Load(Server.MapPath("~/HullUniversityPress/App_Data/" + fileName)); 

Теперь XDocument загружается с содержанием Books.xml:

enter image description here