MVC存储库模式并将记录添加到数据库

时间:2013-12-24 12:06:29

标签: c# asp.net-mvc asp.net-mvc-4

我正在尝试为我正在慢慢开发的Blog功能插入注释记录,以便掌握.NET中的MVC框架。我得到的存储库模式不是.NET。它顺利进来。我有点困难,所以我可以成功地将注释插入我的数据库。

这是继承类,它也使用IDisposable。真的不知道为了什么。可能是垃圾收集,也可能是多重继承。

 public class BlogRepository : IBlogRepository, IDisposable
{
    private BlogDataDataContext _dataContext;

    public BlogRepository() { _dataContext = new BlogDataDataContext(); }

   // #region IBlogRepository Members

    public IList<Entry> Posts()
    {
        var entries = from m in _dataContext.Entries select m;
        return entries.ToList();
    }

    public void InsertComment(Comment comment)
    {
        _dataContext.Comments.InsertOnSubmit(comment);
    }

    public void Save()
    {
        _dataContext.SubmitChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _dataContext.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }




   // #endregion
}

我相信以上所有内容都已实施。我遇到的问题是下一步。这是控制器,使用GET和POST为不同的任务重载BlogPost。我对帖子的第二种方法感兴趣。

public ActionResult BlogPost(int id, string title){
        var viewModel = new ListViewModel(_repository);            
        ViewData["id"] = id;
        return View("BlogPost", viewModel);
    }

    [HttpPost]
    public ActionResult BlogPost(int id, string username, string email, string message)
    {

        if (ModelState.IsValid) {

        // help....

            return RedirectToAction("BlogPost");
        }
        return View();
    }

这是我正在使用的模型,它绑定到View。

 public class ListViewModel
{
    [Required(ErrorMessage = " A Name is required *")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    [StringLength(160, MinimumLength = 2, ErrorMessage = "Must be between 2 & 160 characters in length.")]
    public string AuthorName { get; set; }

    [Required(ErrorMessage = "Email address required *")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    [StringLength(160, MinimumLength = 2, ErrorMessage = "Must be between 2 & 160 characters in length *")]
    [EmailValidation(ErrorMessage = "Must be valid email *")]
    public string AuthorEmail { get; set; }

    [Required(ErrorMessage = " A Message is required *")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    [StringLength(4000, MinimumLength = 2, ErrorMessage = "Must be between 2 & 4000 characters in length *")]
    public string Body { get; set; }

    public ListViewModel(IBlogRepository blogRepository)
    {
        Posts = blogRepository.Posts();
    }

    public IList<Entry> Posts { get; private set; }
    public IList<Comment> Comment { get; private set; }
}

我不知道如何将BlogPost POST方法连接到上面的ListViewModel,后者有一些验证规则,这样我就可以成功地将数据插入到我的数据库中并保持Repository模式的完整性。我遇到困难,因为我只能使用一个模型。如果有人能给我任何洞察我稍微错误的地方,我会非常感激。我知道我很亲密,一旦实现,我可以将这种方法应用到我未来的所有工作中。

2 个答案:

答案 0 :(得分:0)

将您的操作更改为接受模型作为参数,例如

    [HttpPost]
    public ActionResult BlogPost(ListViewModel model)
    {

    }

更新:

从ListViewModel中删除构造函数,使其现在看起来像

public class ListViewModel
{
    [Required(ErrorMessage = " A Name is required *")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    [StringLength(160, MinimumLength = 2, ErrorMessage = "Must be between 2 & 160 characters in length.")]
    public string AuthorName { get; set; }

    [Required(ErrorMessage = "Email address required *")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    [StringLength(160, MinimumLength = 2, ErrorMessage = "Must be between 2 & 160 characters in length *")]
    [EmailValidation(ErrorMessage = "Must be valid email *")]
    public string AuthorEmail { get; set; }

    [Required(ErrorMessage = " A Message is required *")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    [StringLength(4000, MinimumLength = 2, ErrorMessage = "Must be between 2 & 4000 characters in length *")]
    public string Body { get; set; }


    public IList<Entry> Posts { get; private set; }
    public IList<Comment> Comment { get; private set; }
}

然后在你的控制器中添加类似

的存储库
  [HttpPost]
        public ActionResult BlogPost(int id, string username, string email, string message)
        {
var repo = new BlogRepository();

            if (ModelState.IsValid) {

            // help....

                return RedirectToAction("BlogPost");
            }
            return View();
        }

答案 1 :(得分:0)

我认为您对存储库模式的实现有点不对,请看一下本教程:http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

然后,对于您的问题,我认为您的博客和评论模型应如下所示:

public class BlogPost
{
  // properties such as id, title, body, etc. Don't forget to add validation attributes.

  public virtual IList<Comment> Comments {get;set;}
}

public class Comment
{
  // again properties such as id, author, e-mail, etc. and validation

  // the FK to BlogPost
  public int BlogPostId {get;set;}
  public virtual BlogPost BlogPost {get;set;}
}

对于这两个实体,您应该按照该教程中的说明创建一个存储库。在MVC中:

public ActionResult AddComment(int blogPostId)
{
  return View(new Comment { BlogPostId = blogPostId} ); // maybe some validating on the blogPostId
}

[HttpPost]
public ACtionResult AddComment(Comment model)
{
  // do some manual validating yourself first, e.g. check if the model.BlogPostId still exists. One could have changed this to test your security...

  if (ModelState.IsValid)
  {
    // save the new comment here, for examle:
    var commentRepo = new CommentRepository();
    commentRepo.Insert(model);
    commentRepo.Save();

    return Redirect.... // redirect to for example the post page
  }
  return View(model);
}