【问题标题】:IEnumerable<SelectListItem> in C# mvcC# mvc 中的 IEnumerable<SelectListItem>
【发布时间】:2015-11-07 11:57:05
【问题描述】:

我有两个表,Student (name, id, UniversityID) 和 Universities (Id, Name)。一个包含有关学生详细信息的信息,另一个包含有关大学的信息。在第一个表中,我存储了与Universities.ID 匹配的Student.UniversityID。大学在有关学生详细信息的表单中显示为下拉列表。

我的问题是,当我编辑特定学生时,如何在添加学生详细信息时在之前的表单中选择大学名称,预选。

到目前为止,我正在做的是像这样填充下拉列表

public ActionResult Edit(int? id)
{
    IEnumerable<SelectListItem> items = db.Universities
        .Select(c => new SelectListItem
        {
            Value = c.UniversityId.ToString(),
            Text = c.UniversityName.ToString(),
            Selected = true,
        });
    ViewBag.UniversityID = items;
}

我想最好的办法是在两个表之间加入基于

{select UniversityName from Universities Join Student where Student.UniversityID=Universities.ID }

知道如何在 Linq 中加入这两个表并使用 IEnumerable SelectListItem 选择符合此条件的 UniversityName 吗???

【问题讨论】:

    标签: c# linq ienumerable selectlistitem


    【解决方案1】:

    如果您使用的是 EntityFramework,您可以指定 ForeignKey 约束,在这种情况下您可以这样做:

    db.Students.Select(student => new {
        UniversityName = student.University.UniversityName
    })
    

    要添加 ForeignKey 约束,在你的 EntityFramework 数据实体中做:

    [Table("Student")]
    public class Student
    {
        [Key] public int Id { get; set; }
        public string Name { get; set; }
        public int UniversityId { get; set; }
    
        [ForeignKey("UniversityId")] public University University { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 2016-05-11
      • 2014-01-12
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多