MVC 3在多对多关系上设置默认值(iCollection)

时间:2013-02-23 11:18:07

标签: asp.net-mvc asp.net-mvc-3

我现在正在学习MVC 3(代码优先),我已经学到了很多,感谢asp.net上的一些很棒的教程以及有关stackoverflow的一些问题,但我无法解决问题。我正在尝试设置默认值。当有人提出问题时,默认情况下该问题的状态必须为3(=未答复)。由于这篇文章,我设法设置了这个帖子:Default value in an asp.net mvc view model 但现在我正试图为很多关系做同样的事情。 (在QuestionModel公共虚拟ICollection类别中)

有人可以帮我解决这个问题。

这是我的QuestionModel(Question.cs)

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace MvcDatabase.Models
{
    public class Question
    {
        [Key]
        public int QuestionID { get; set; }

        [DisplayFormat(DataFormatString="{0:d}", ApplyFormatInEditMode=true)]
        [Display(Name="Datum")]
        public DateTime Date { get; set; }

        [Required(ErrorMessage="Naam is een verplicht veld.")]
        [MaxLength(100, ErrorMessage="Naam kan maximum 100 karakters bevatten")]
        [Display(Name="Naam")]
        public string Author { get; set; }

        [Required(ErrorMessage="E-mail is een verplicht veld.")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email")]
        public string MailAuthor { get; set; }

        [Required(ErrorMessage="Onderwerp is een verplicht veld.")]
        [MaxLength(100, ErrorMessage="Onderwerp kan maximum 100 karakters bevatten.")]
        [Display(Name="Onderwerp")]
        public string Title { get; set; }

        [Required(ErrorMessage="Bericht is een verplicht veld.")]
        [Display(Name="Bericht")]
        public string Message { get; set; }

        public virtual ICollection<Category> Categories { get; set; }
        public virtual ICollection<Reaction> Reactions { get; set; }

        [ForeignKey("Status")]
        public int StatusID { get; set; }
        public virtual Status Status { get; set; }

        public Question()
        {
            StatusID = 3;
        }
    }
}

这是CategoryModel(Category.cs)

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace MvcDatabase.Models
{
    public class Category
    {
        [Key]
        public int CategoryID { get; set; }

        [Required(ErrorMessage="Omschrijving is een verplicht veld.")]
        [MaxLength(100, ErrorMessage = "Omschrijving kan maximum 100 karakters bevatten.")]
        [Display(Name="Categorie omschrijving")]
        public string Description { get; set; }

        public virtual ICollection<Question> Questions { get; set; }
    }
}

这是DbContextModel(TestotheekDBContext.cs)

using System.Data.Entity;

namespace MvcDatabase.Models
{
    public class TestotheekDBContext: DbContext
    {
        public DbSet<Status> Statuses { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Question> Questions { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Reaction> Reactions { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Question>()
                .HasMany(qc => qc.Categories)
                .WithMany(cq => cq.Questions)
                .Map(m => m.MapLeftKey("QuestionID")
                    .MapRightKey("CategoryID")
                    .ToTable("QuestionsWithCategory"));
        }
    }
}

如果您需要Controller中的代码

        public ActionResult Create()
        {
            return View(new Question());
        } 

        //
        // POST: /Default4/Create

        [HttpPost]
        public ActionResult Create(Question question)
        {
            var vraag = new Question();
            vraag.Date = DateTime.Now;
            vraag.Author = question.Author;
            vraag.MailAuthor = question.MailAuthor;
            vraag.Title = question.Title;
            vraag.Message = question.Message;

            if(ModelState.IsValid)
            {
                db.Questions.Add(vraag);
                db.SaveChanges();
                return RedirectToAction("Index","Home");
            }
            return View(question);
        }

(尚未测试返回RedirectToAction)

修改

这是我目前得到的结果: enter image description here 正如您在第一部分(第一个表)中的最后一个问题中所看到的那样,没有类别(字段为空),这必须与该表中没有类别的所有其他问题相同,因为管理员必须分配一个(或更多)。

2 个答案:

答案 0 :(得分:0)

您需要将现有类别从db上下文附加到您的实体。在控制器中执行此操作通常不是一个好主意(垃圾收集器,非现有实体的例外)。我会在你的控制器创建动作中做到这一点

 [HttpPost]
 public ActionResult Create(Question question)
 {
     var vraag = new Question();
     vraag.Date = DateTime.Now;
     vraag.Author = question.Author;
     vraag.MailAuthor = question.MailAuthor;
     vraag.Title = question.Title;
     vraag.Message = question.Message;

     // Add the default categories here!
     vraag.Categories = db.Categories.Where(c => c.SomeCriteria).ToList();

     if(ModelState.IsValid)
     {
         db.Questions.Add(vraag);
         db.SaveChanges();
         return RedirectToAction("Index","Home");
     }

     return  View(question);
 }

答案 1 :(得分:0)

所以答案并不完全是Saintedlame所说的,但他确实以正确的方式指出了我。首先,在调试之后,我看到行var vraag = new Question()是无用的,因为几乎所有内容都是有问题的。我只需要添加日期和类别。再次,谢谢Saintedlame!

这是实际的ActionResult:

        [HttpPost]
        public ActionResult Create(Question question)
        {
            question.Date = DateTime.Now;
            if (question.Categories == null) 
            {
                var category = db.Categories
                    .Include(q => q.Questions)
                    .Where(q => q.CategoryID == 1)
                    .ToList();
                question.Categories = category;
            }

            if(ModelState.IsValid)
            {
                db.Questions.Add(question);
                db.SaveChanges();
                return RedirectToAction("Index","Home");
            }
            return View(question);
        }

结果如下:

enter image description here