如何阅读EF 5中的NotMapped属性?

时间:2013-03-02 23:52:37

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

我无法弄清楚如何访问标记为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();

我对Section的上下文是:

    [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;
        }
    }
}

1 个答案:

答案 0 :(得分:5)

由于它未映射,因此无法在查询中使用...您必须先实现对象才能访问该属性...

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()