【问题标题】:MVC4 EF DB First - How to access a models foreign key (ICollection)MVC4 EF DB First - 如何访问模型外键(ICollection)
【发布时间】:2013-02-25 02:12:30
【问题描述】:

我创建了一个带有包含外键的表的 MSSQL 数据库。然后我创建了一个新的 MVC 4 Web 应用程序。我使用实体框架来生成我的控制器/模型/视图。在模型中,使用外键链接的表显示为 ICollections。例如:

 public partial class Test
{

    public Test()
    {
        this.Questions = new HashSet<Question>();
        this.Users = new HashSet<User>();
    }

    public int testId { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public Nullable<int> pointValue { get; set; }
    public Nullable<int> numberOfQuestions { get; set; }

    public virtual ICollection<Question> Questions { get; set; }
    public virtual ICollection<User> Users { get; set; }

    }
}

我的问题是如何在视图中访问存储在这些 ICollections 中的数据? Test.Questions[x]

【问题讨论】:

  • 为了澄清,你有QuestionUser的模型吗?
  • ((Test)test).Questions[0].QuestionType?它是一个集合,因此您必须先引用单个实例,然后才能访问其属性。

标签: entity-framework asp.net-mvc-4 model foreign-key-relationship icollection


【解决方案1】:

ICollection&lt;T&gt; 就像IList&lt;T&gt;T[] 一样,因此您必须先在集合中获取一个元素,然后再引用它的属性。例如

Test test = testService.Get(1);
Question question = test.Questions.FirstOrDefault(); // using System.Linq;
if (question.quertionType == ....)
{
}

【讨论】:

    【解决方案2】:

    这比我预期的要简单。我只需要使用一个 foreach 循环:

        @foreach (var question in item.Questions)
        {
            <td>@question.question1</td>
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2015-01-16
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多