A_l*_*lan 3 c# asp.net asp.net-mvc entity-framework
我正在做MVC 3 Web应用程序并且有很奇怪的问题.这是一些代码:
型号声明:
public class Project
{
public int ID { get; set; }
[Required(ErrorMessage = "Write a title.")]
public string Title { get; set; }
public DateTime TimeAdded { get; set; }
[Required(ErrorMessage = "Write some description.")]
[MaxLength(int.MaxValue)]
public string Content { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int ID { get; set; }
[Required()]
public int ProjectID { get; set; }
public DateTime TimeAdded { get; set; }
[Required()]
public string Text { get; set; }
public Project project { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class HomeController : Controller
{
dataDBContext db = new dataDBContext();
//
// GET: /Home
public ActionResult Index()
{
var comments = from c in db.Comments
select c;
var projects = from p in db.Projects
orderby p.TimeAdded descending
select p;
return View(projects.ToList());
}
Run Code Online (Sandbox Code Playgroud)
我找到了简单的解决方法:
public ActionResult Index()
{
var projects = from p in db.Projects
orderby p.TimeAdded descending
select p;
foreach (var p in projects)
{
var comments = from c in db.Comments
where c.ProjectID == p.ID
select c;
p.Comments = comments.ToList();
}
return View(projects.ToList());
}
Run Code Online (Sandbox Code Playgroud)
但它看起来(根据第2点),这可以自动填充SOMEHOW :)
有什么办法吗?
另一个尝试基于给定的答案:
public class HomeController : Controller
{
dataDBContext db;
public HomeController()
{
db = new dataDBContext();
db.Configuration.LazyLoadingEnabled = false;
}
//
// GET: /Home
public ActionResult Index()
{
var projects = from p in db.Projects
orderby p.TimeAdded descending
select p;
return View(projects.ToList());
}
Run Code Online (Sandbox Code Playgroud)
我有外键.我添加了LazyLoadingEnabled.有project.ToList(),它不起作用.
基于第二个答案,我做了类似的事情:
public class HomeController : Controller
{
dataDBContext db;
public HomeController()
{
db = new dataDBContext();
}
//
// GET: /Home
public ActionResult Index()
{
var projects = from p in db.Projects
orderby p.TimeAdded descending
select p;
var comments = from c in db.Comments
select c;
List<Comment> l = comments.ToList();
return View(projects.ToList());
}
Run Code Online (Sandbox Code Playgroud)
我只添加了comments.ToList(),它正在工作.但我不确定这是否是正确的解决方案.可能比我的解决方法更好(第3点).有什么建议?
谢谢
如果您在评论和项目之间有外键,则可以执行以下操作
db.ContextOptions.LazyLoadingEnabled = false;
var projects = from p in db.Projects.Include("Comments")
orderby p.TimeAdded descending
select p;
Run Code Online (Sandbox Code Playgroud)
当您执行.ToList()时,它将加载所有项目的所有注释.您将能够通过项目对象的导航属性"注释"访问数据.
| 归档时间: |
|
| 查看次数: |
725 次 |
| 最近记录: |