【问题标题】:EF code first: using Linq with many-to-many relationshipEF 代码优先:使用具有多对多关系的 Linq
【发布时间】:2012-11-16 15:38:24
【问题描述】:

我正在使用带有 EF 代码优先方法的 MVC 4。我有两个简单的对象。这些是他们的 POCO 类:

public class Activity
{
        //Primitive Properties
        [HiddenInput]
        public int Id { get; set; }

        [Required]
        public int LengthInMinutes { get; set; }

        public string AdditionalInfo { get; set; }

        [Required]
        public bool Archive { get; set; }

        //Navigation Properties
        public virtual User User { get; set; }
        public virtual ActivitySet ActivitySet { get; set; }
        public virtual ICollection<Company> Companies { get; set; }
        public virtual ICollection<Description> Descriptions { get; set; }
}

public class Company
{
        //Primitive Properties
        [HiddenInput]
        public int Id { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public bool Archive { get; set; }

        //Navigation Properties
        public virtual ICollection<Activity> Activities { get; set; }
}

现在,我有了使用 foreach 循环遍历的通用活动列表。循环时,我想为与列表中的活动相关的每个公司写一个名称。这是我想出的代码:

@foreach (Activity a in Model)
{
    <p>@a.Companies.Where(d => d.Activities.FirstOrDefault(y => y.Id == a.Id)).Single()</p>
}

不幸的是,当我构建项目时它给了我编译错误。然后如何访问具有多对多关系的元素的详细信息

【问题讨论】:

    标签: asp.net-mvc linq entity-framework-4


    【解决方案1】:

    你可以这样尝试:

    @foreach (Activity a in Model)
    {
        <p>@string.Join(",", a.Companies.Select(c => c.Title))</p>
    }
    

    它应该列出给定活动的所有公司名称,用逗号分隔。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      相关资源
      最近更新 更多