2015-07-18 8 views
5

Buon giorno, sono nuovo su ASP.NET e non riesco a capire perché il mio codice non funziona. Ho il modello:ASP.NET salva il modello di entità complessa

using System.ComponentModel.DataAnnotations; 
using System.Drawing; 
using System.Globalization; 

namespace WebApp.Models 
{ 
public class News 
{ 
    public int NewsId { get; set; } 
    public string title { get; set; } 
    public string description { get; set; } 
    public virtual Picture picture { get; set; } 
    public int guid { get; set; } 
} 

public class Picture 
{ 
    public int PictureId { get; set; } 
    public byte[] image { get; set; } 
    public int width { get; set; } 
    public int height { get; set; } 
    public int hash { get; set; } 
} 
} 

E io sto cercando di creare un nuovo "News" il modulo di posta:

// POST: News/Create 
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(News news, HttpPostedFileBase uploadImage) 
    { 
     if (ModelState.IsValid && uploadImage != null) 
     { 
      byte[] imageData = null; 
      using (var binaryReader = new BinaryReader(uploadImage.InputStream)) 
      { 
       imageData = binaryReader.ReadBytes(uploadImage.ContentLength); 
      } 
      news.picture = new Picture() 
      { 
       hash = 0, 
       image = imageData, 
       width = 0, 
       height = 0 
      }; 
      db.News.Add(news); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(news); 
    } 

Ma quando ho recuperare i dati da db ottengo nulla un'eccezione di puntatore: , quando ho chiamato debugger, ho capito che il valore "news.picture" è nullo. Ma prima di db.SaveChanges() il 100% non è nullo. Sembra che sto facendo qualcosa di stupidamente sbagliato, ma non riesco a trovarne qualcuno1 che ha affrontato questo problema. Grazie.

+0

Non so perché, ma quando aggiungo proprietà virtuale tutte le opere : "immagine pubblica virtuale Picture {get; set;}" –

+0

Sì, la proprietà virtuale dice che questo sarà navigato pigramente. Generalmente ognuno ha 'public virtual' su tutte le proprietà di navigazione –

+0

Diverse modifiche apporterei - in primo luogo mettere un 'public int PictureId {get; impostato;} 'sul modello di notizie, che inserirà una chiave esterna lì. Quindi attribuilo a '[ForeignKey (" Picture ")]' dove '" Picture "' è la proprietà di navigazione virtuale. Nell'entità dell'immagine, è possibile rimuovere 'Picture' dal nome' Id' come con l'entità news. Questo lo rende più pulito –

risposta

0

Non so perché, ma quando aggiungo proprietà virtuale tutte le opere:

public virtual Picture picture { get; set; } 
0

provare le seguenti

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(News news, HttpPostedFileBase uploadImage) 
    { 
     if (ModelState.IsValid && uploadImage != null) 
     { 
      byte[] imageData = null; 
      using (var binaryReader = new BinaryReader(uploadImage.InputStream)) 
      { 
       imageData = binaryReader.ReadBytes(uploadImage.ContentLength); 
      } 
      var picture = new Picture() 
      { 
       hash = 0, 
       image = imageData, 
       width = 0, 
       height = 0 
      }; 
      db.Pictures.Add(picture); // make sure that the picture was tracked by the EF 
      news.picture = picture; 
      db.News.Add(news); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(news); 
    } 
+1

Ciò non importa, se il modello è stato collegato tramite una proprietà di navigazione, creerà l'entità nel database e la assocerà all'entità di notizie. –

0

vorrei fare le seguenti modifiche e vedere se aiuta.

namespace WebApp.Models 
{ 
    public class News 
    { 
     public int Id { get; set; } 
     public string Title { get; set; } 
     public string Description { get; set; } 

     [ForeignKey("Picture")] 
     public int PictureId { get; set; } 
     public virtual Picture Picture { get; set; } 

     // not sure why this is here 
     public int guid { get; set; } 
    } 

    public class Picture 
    { 
     public int Id { get; set; } 

     public byte[] ImageData { get; set; } 
     public string ContentType { get; set; } 

     public int width { get; set; } 
     public int height { get; set; } 
     public int hash { get; set; } 
    } 
} 

Il controllore:

// POST: News/Create 
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(NewsDto news, HttpPostedFileBase uploadImage) 
{ 
    if (ModelState.IsValid && uploadImage != null) 
    { 
     var imageData = byte[uploadImage.ContentLength]; 
     using (var binaryReader = new BinaryReader(uploadImage.InputStream)) 
     { 
      imageData = binaryReader.ReadBytes(uploadImage.ContentLength); 
     } 

     var newsEntity = new New { 
      Title = news.Title, 
      Description = news.Description, 
      Picture = new Picture() 
      { 
       ImageData = imageData, 
       ContentType = contentType // I would get that from the HttpPostedFileBase 
      } 
     } 

     // I always wrap my database connections in a using. 
     using (var db = new DbContext()) { 
      db.News.Add(newsEntity); 
      db.SaveChanges(); 
     } 

     return RedirectToAction("Index"); 
    } 
    return View(news); 
} 
Problemi correlati