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

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

我有两个类,CompanyCompanyAddress

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

通过 Entity Framework ,我尝试包含属于公司的所有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; }
}

CompanyAddress 类

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 Action 调用方法

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

        return View(comp);
    }

欢迎所有建议!感谢您抽出时间。

最佳答案

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

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

关于linq - 如何在 LINQ 查询中包含相关表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23643858/

相关文章:

linq - LINQ skip & take 是否有不错的性能?

c# - LINQ 中的 GroupBy 保证

c# - 如何使用 Group by 在 Linq 语句中引入 Let 关键字

entity-framework - Entity Framework CTP5 代码优先映射 - 同一个表中的外键

c# - JsonPatchDocument 访问 ICollection

asp.net-mvc-4 - 从 identityserver4 登录的 asp.net mvc 出现 invalid_request 错误

asp.net - 在处理请求之前找出 Controller 的名称和操作

c# - LINQ Distinct 运算符,忽略大小写?

c# - 使用 Entity Framework 读取时出错

c# - 将 IDictionary<Guid,string> 转换为 IEnumerable<SelectListItem>