コード例 #1
0
        public ActionResult Create([Bind(Include = "Name,Description,Genre,Price,Publisher")] Magazine magazine)
        {
            if (ModelState.IsValid)
            {
                Magazine mag = new Magazine
                {
                    Name = magazine.Name,
                    Description = magazine.Description,
                    Genre = magazine.Genre,
                    Price = magazine.Price,
                    Publisher = magazine.Publisher
                };

                var pubList = from n in db.Publishers
                              where n.Name == magazine.Publisher
                              select n;

                if (!pubList.Any())
                {
                    Publisher pub = new Publisher {Name = magazine.Name };
                    db.Publishers.Add(pub);
                    db.SaveChanges();
                }

                try
                {
                    db.Magazines.Add(mag);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View("~/Views/Home/Index.cshtml", null);
                }
            }

            return View(magazine);
        }
コード例 #2
0
        public ActionResult AddMagazine()
        {
            String mName = Convert.ToString(Request["name"].ToString());
            String mDescription = Convert.ToString(Request["description"].ToString());
            String mGenre = Convert.ToString(Request["genre"].ToString());
            decimal mPrice = Convert.ToDecimal(Request["price"].ToString());
            String mPublisher = Convert.ToString(Request["publisher"].ToString());

            Magazine magazine = new Magazine { Name = mName, Description = mDescription, Genre = mGenre, Price = mPrice, Publisher = mPublisher };

            var pubList = from n in db.Publishers
                          where n.Name == magazine.Publisher
                          select n;

            var genreList = from m in db.Genres
                            where m.Name == magazine.Genre
                            select m;

            if (!genreList.Any())
            {
                Genre gen = new Genre { Name = magazine.Genre };
                db.Genres.Add(gen);
                db.SaveChanges();
            }

            if (!pubList.Any())
            {
                Publisher pub = new Publisher { Name = magazine.Publisher };
                db.Publishers.Add(pub);
                db.SaveChanges();
            }

            db.Magazines.Add(magazine);
            db.SaveChanges();

            return View("~/Views/Magazines/Index.cshtml", db.Magazines.ToList());
        }