如何在LINQ查询中包含相关表?

时间:2014-05-14 00:42:29

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

我有两个类,公司公司地址

对于每个公司,可以有多个 CompanyAddresses ,例如发票地址和通信地址。

通过实体框架,我尝试包含属于公司的所有 CompanyAddresses 。但是,我一直收到以下调试错误:

System.Data.Entity.dll中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理 附加信息:指定的包含路径无效。 EntityType“StatelyTechAdmin.Models.Company”未声明名为“CompanyAddresses”的导航属性。

有人可以告诉我为什么我不能在LINQ查询中包含所有地址吗?请注意我对Entity Framework很新。

公司类

public class Company
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public virtual long CompanyId { get; set; }

    [Required]
    [Display(Name = "Company Name")]
    public virtual string Name { get; set; }

    public virtual DateTime CreatedDate { get; set; }

    public virtual IEnumerable<CompanyAddress> CompanyAddresses { get; set; }
}

公司地址类

public class CompanyAddress
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public virtual long CompanyAddressId { get; set; }

    [Required]
    public virtual long CompanyId { get; set; }

    [ForeignKey("CompanyId")]
    public virtual Company Company { get; set; }

    [Required]
    public virtual int CompanyAddressTypeId { get; set; }

    [ForeignKey("CompanyAddressTypeId")]
    public virtual CompanyAddressType CompanyAddressType { get; set; }

    [Display(Name = "Address 1")]
    public virtual string Address1 { get; set; }

    [Display(Name = "Address 2")]
    public virtual string Address2 {get; set; }

    [Display(Name = "Town")]
    public virtual string Town { get; set; }

    [Display(Name = "City")]
    public virtual string City { get; set; }

    [Required]
    public virtual long CountyId { get; set; }

    [ForeignKey("CountyId")]
    [Display(Name = "County")]
    public virtual County County { get; set; }

    [Required]
    [Display(Name = "Postal Code")]
    public virtual string PostalCode { get; set; }

    public virtual DateTime CreatedDate { get; set; }
}

从MVC操作调用方法

public ActionResult Index()
    {
        var comp = db.Companies.Include(a => a.CompanyAddresses).ToList();

        return View(comp);
    }

欢迎所有建议!谢谢你的时间。

1 个答案:

答案 0 :(得分:2)

您不能将IEnumerable用于导航属性。您需要使用ICollection或从中派生的类型。

How do I load related entities of type IEnumerable<T>