【问题标题】:How to include related table in LINQ query?如何在 LINQ 查询中包含相关表?
【发布时间】:2014-07-01 20:54:44
【问题描述】:

我有两个班级,CompanyCompanyAddress

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

通过实体框架,我试图包含属于 Company 的所有 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 动作调用方法

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

        return View(comp);
    }

欢迎所有建议!感谢您的宝贵时间。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 看准了!非常感谢您的帮助。
    猜你喜欢
    • 2023-04-02
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2022-01-27
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    相关资源
    最近更新 更多