Stan
Stan

Reputation: 26511

Entity Framework - Best way to tie one -> many relation

I want to add images to my item using POCO approach. In order for everything to work I need to modify my view/controller.

Item

namespace POCOExample.Models
{
    public class Item
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Info { get; set; }
        public List<Image> Images { get; set; }
    }
}

Image

namespace POCOExample.Models
{
    public class Image
    {
        public int ID { get; set; }
        public int ItemID { get; set; }
        public Item Item { get; set; }
        public string FileName { get; set; }
    }
}

Controller Create(POST) action

[HttpPost]
public ActionResult Create(Item item, List<HttpPostedFileBase> iamges)
{
    if (ModelState.IsValid)
    {
        // Added code START
        foreach (var image in images)
        {
            item.Images.Add(new Image {
                FileName = Infrastructure.Image.Upload(image) // Returns file name, just what I need
            });
        }
        // Added code END

        db.Items.Add(item);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(item);
}

Question

This code works, however I wonder if I'm doing this is the most optimal/correct way?

Upvotes: 0

Views: 264

Answers (1)

rouen
rouen

Reputation: 5124

Yes, you approach is correct.

And since there is no place for correction, I would like to give you philosophical advice: don't even ask yourself if it is optimal. Answer to this question would be in 99% NO, but don't even think to give a shit about that and turn your simple, correct, and maintanable code to some "optimal" mess without numbers in your hands, proving that this particular piece of code is causing real-world performance problem :)

Upvotes: 1

Related Questions