【发布时间】:2013-12-31 01:05:04
【问题描述】:
这是我的 ListView 模型,它与我建立的名为 Comment 的数据库表相对应。
public int EntryId { get; set; }
public DateTime Posted { get; set; }
public string AuthorIp { get; set; }
[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 ListView(IBlogRepository blogRepository)
{
Posts = blogRepository.Posts();
}
public ListView(){ }`
我需要将一些属性添加到我的 Comment 表中。我正在使用或至少尝试使用 IRepository 框架。是这样的……
public interface IBlogRepository : IDisposable
{
IList<Entry> Posts();
void InsertComment(Comment comment);
void Save();
}
这是我的继承类...
public class BlogRepository : IBlogRepository, IDisposable
{
private BlogDataDataContext _dataContext;
public BlogRepository() { _dataContext = new BlogDataDataContext(); }
// #region IBlogRepository Members
public void InsertComment(Comment comment)
{
_dataContext.Comments.InsertOnSubmit(comment);
}
public void Save()
{
_dataContext.SubmitChanges();
}
所以我像这样从我的 BlogController 调用上面的 InsertComment。
[HttpPost]
public ActionResult BlogPost(ListView pModel)
{
pModel.Posted = DateTime.Now;
_repository.InsertComment( // Cannot pass pModel as is not Comment type.
return RedirectToAction("BlogPost");
}
所以我的问题是我的 ListView pModel 已传入,但它不是 Comment 类型,所以我无法正确插入它。我需要我的 ListView 模型,因为它包含额外的验证规则和几个构造函数。任何人都知道我哪里出错了。
我是否需要创建一个直接反映我正在添加的数据库表的模型。那么我在哪里移动我的构造函数和其他验证规则?感觉我需要两个模型。一个在另一个之上。我现在非常接近理解这一点。
提前致谢。
【问题讨论】:
-
在实体框架中使用存储库模式不是一个好主意。实际上,它只是添加了不必要的抽象层。您已经在 EF 中拥有通用存储库和通用工作单元。
-
@RomanPushkin 这并不总是正确的,因为大多数人已经在 EF 中使用了存储库模式。即使在 EF 中加入了 UoW / Repo 模式。
-
我认为我的问题不是完全理解所有这些方法之间的区别,所以我将它们混合在一起并破解我的方式。我感谢您的帮助。所以 EF 是通过模型将表映射到视图。对我来说,这感觉很像序列化。我会继续努力的。我已经下载了 contuso 大学项目。我想我会尝试做一些这样的事情,看看我能得到什么。
标签: asp.net-mvc asp.net-mvc-4 entity-framework-4