2015-07-18 10 views
5

Добрый день, я новичок в ASP.NET, и я не могу понять, почему мой код не работает. У меня есть модель:ASP.NET сохранить сложную модель сущности

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

И я пытаюсь создать новую «Новости» с помощью почтовой формы:

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

Но когда я извлечения данных из БД я получаю нулевой исключением указатель: , когда я звонил отладчик, я считаю, что значение «news.picture» равно null. Но до db.SaveChanges() он на 100% не равен нулю. Похоже, я делаю что-то глупое, bcs. Я не могу найти кого-то, кто столкнулся с этой проблемой. Спасибо.

+0

Я не знаю почему, но когда я добавить виртуальную собственность все работы : "public virtual Picture picture {get; set;}" –

+0

Да, виртуальная собственность говорит, что это будет лениво перемещаться. Как правило, у всех есть 'public virtual' на всех свойствах навигации –

+0

Несколько изменений, которые я бы сделал - сначала положил' public int PictureId {get; set;} 'в новостной модели, в которую будет добавлен внешний ключ. Тогда атрибут будет «[ForeignKey (« Изображение »)], где' 'Picture" 'является свойством виртуальной навигации. В объекте изображения вы можете удалить 'Picture' из имени' Id', как и для объекта новостей. Это делает его более чистым. –

ответ

0

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

public virtual Picture picture { get; set; } 
0

попробуйте следующее

[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

Это не имеет значения, если вы привязали модель с помощью свойства навигации, она создаст объект в базе данных и свяжет его с объектом новостей. –

0

Я хотел бы сделать следующие изменения и посмотреть, если это помогает.

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

Контроллер:

// 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); 
} 
Смежные вопросы