asp.net - mvc poco list is null: add new item -
i have following poco in mvc4 project:
public class gallery : modelbase { public string name { get; set; } public string description { get; set; } public bool ispublic { get; set; } public string thumbnailpath { get; set; } [foreignkey("id")] public icollection<galleryimage> images { get; set; } }
if create new gallery entity, images collection null. how can add new image (in case) uninitialized list? code adding looks this:
guid ggallery = guid.parse(request.form.getvalues("galleryid")[0]); gallery gallery = db.galleries.where(g => g.id == ggallery).include(g => g.images).first(); galleryimage.id = guid.newguid(); galleryimage.createdbyuserid = websecurity.currentuserid; galleryimage.insertdate = datetime.now; galleryimage.lastmoddate = datetime.now; db.galleryimages.add(galleryimage); if (gallery.images == null) gallery.images = new list<galleryimage>(); gallery.images.add(galleryimage); db.savechanges();
the code breaks @ runtime exception (sorry in german):
ein objekt vom typ 'system.collections.generic.list`1[[gallery.models.galleryimage, gallery, version=1.0.0.0, culture=neutral, publickeytoken=null]]' kann für eine entityreference vom typ 'gallery.models.galleryimage' nicht als value-eigenschaft festgelegt oder daraus entfernt werden.
now how can add new item uninitialized collection?
you have problem in poco , should follows:
public class gallery : modelbase { public string name { get; set; } public string description { get; set; } public bool ispublic { get; set; } public string thumbnailpath { get; set; } // remove foreignkey attr. should in galleryimage public icollection<galleryimage> images { get; set; } }
then have many problems in code.
first should use guid.tryparse
or validate guid valid guid.
then should use request.form.getvalues("galleryid")[0]
can npe.
moreover, should avoid using first()
, should use firstordefault
, more defensive, is: check if null or not.
and yet, have more problems, once load gallery, can add gallery image images , call db.savechanges();
Comments
Post a Comment