【发布时间】:2017-07-19 07:41:27
【问题描述】:
当我在做一个项目时,我在一个只能从表中检索唯一值的地方感到困惑。为此,我在 linq 查询中使用了不同的 groupby 子句,但出现了一些错误。我有两个表,类别表的 id 是外键,我只需要从另一个图库表中检索不同的 id
型号
public partial class Gallery
{
public int Id { get; set; }
public int CategoryId { get; set; }
public string ImageTitle { get; set; }
public string Image { get; set; }
public virtual Category Category { get; set; }
}
public Category()
{
this.Galleries = new HashSet<Gallery>();
}
public int Id { get; set; }
public string CategoryName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Gallery> Galleries { get; set; }
}
这是模型,categoryid 是画廊类的外键
控制器
public ActionResult GalleryCata()
{
var res = db.Galleries.ToList();
return View(res);
}
查看
@model List<ThaniyamBank.Models.Gallery>
@for (var j = 0; j < Model.Count(); j++)
{
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
<div class="hovereffect">
<img src="@Url.Content("~/GalleryImages/" + @Html.DisplayFor(m => m[j].Image))" class="img-responsive" alt="" />
<div class="overlay">
<h2>@Html.DisplayFor(m => m[j].Category.CategoryName) </h2>
<a class=" fancybox info " href="@Url.Content("~/GalleryImages/" + @Html.DisplayFor(m => m[j].Image))" data-fancybox-group="gallery"><i class="fa fa-eye" aria-hidden="true"></i></a>
<a class="info " href="gallery.html"><i class="fa fa-link" aria-hidden="true"></i></a>
</div>
</div>
</div>
}
我需要根据类别显示图像。当我运行应用程序时,我从表中获取所有图像,而不是基于类别。谁能帮我解决这个问题??
【问题讨论】:
-
我没有看到任何“distinct , groupby”。展示您尝试过的内容,这可能会澄清您所说的“独特”的含义。并显示错误。 “我遇到了一些错误”并不意味着什么。
-
当我给 var res = db.Galleries.Select(x=>x.CategoryId).Distinct().ToList();在控制器中,出现错误传递到字典中的模型项的类型为“System.Collections.Generic.List
1[System.Int32]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[A.Models.Gallery]”。 -
很清楚的错误信息,不是吗?
-
通过将列表更改为 ienumerable 显示错误无法使用 [] 将索引应用于“IEnumerable
”类型的表达式。如果我只是写没有列表和 ienumerable 的 db 那么我怎样才能从表中获取数据集合??
标签: sql-server asp.net-mvc linq asp.net-mvc-4 razor