【问题标题】:How to read NotMapped properties in EF 5?如何读取 EF 5 中的 NotMapped 属性?
【发布时间】:2013-03-02 23:52:37
【问题描述】:

我不知道如何访问标记为 NotMapped 的属性,因此我可以打印它。当我尝试访问它时,我得到了

LINQ to Entities 不支持指定的类型成员“LinkAddress”。仅支持初始化器、实体成员和实体导航属性。

我的 LINQ 查询是:

(from n in db.Navigation
                                  join s in db.Sections on n.SectionID equals s.SectionID
                                  join sl in db.Locale_Sections on s.SectionID equals sl.SectionID
                                  where n.Category == "Books" && sl.CultureID == 1
                                  select new
                                  {
                                      s.LinkAddress,
                                      sl.Title,
                                  }).ToList();

我的部分上下文是:

    [Table("Section")]
public class Section
{
    [Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Int16 SectionID { get; set; }

    public Int64 LogoFileID { get; set; }

    [ForeignKey("LogoFileID")]
    public virtual File File { get; set; }

    [Required, MaxLength(15), Column(TypeName = "varchar")]
    public string RouteName { get; set; }

    [Required, MaxLength(15), Column(TypeName = "varchar")]
    public string Type { get; set; }

    public virtual ICollection<Locale_Section> Translations { get; set; }

    [NotMapped]
    public string LinkAddress
    {
        get
        {
            return Type + "/" + RouteName;
        }
    }
}

【问题讨论】:

    标签: linq webforms entity-framework-5 asp.net-4.5


    【解决方案1】:

    由于它没有被映射,它不能在查询中使用……你必须先实现对象,然后才能访问属性……

    var materialised = (from n in db.Navigation
         join s in db.Sections on n.SectionID equals s.SectionID
         join sl in db.Locale_Sections on s.SectionID equals sl.SectionID
         where n.Category == "Books" && sl.CultureID == 1
         select new
         {
              s,
              sl.Title,
         }).ToList()
    
    // This bit is done in CLR
    return materialised.Select(m => new 
    {
        m.s.LinkAddress,
        m.Title
    });
    

    或者,您可以将您的逻辑带入有效的查询中......

    (from n in db.Navigation
     join s in db.Sections on n.SectionID equals s.SectionID
     join sl in db.Locale_Sections on s.SectionID equals sl.SectionID
     where n.Category == "Books" && sl.CultureID == 1
     select new
     {
         LinkAddress = s.Type + "/" + s.RouteName,
         sl.Title,
     }).ToList()
    

    【讨论】:

    • 感谢我使用您的 alt 解决方案,因为它的代码更少,阅读更清晰。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多