简体   繁体   English

扩展POCO实体上的Linq to Entities

[英]Linq to Entities on extended POCO entities

I am using EF5 and using their code generator I got the POCO classes generated. 我正在使用EF5,并使用他们的代码生成器生成了POCO类。 Here is an example of one: 这是一个示例:

public partial class School
    {
        public School()
        {
            this.Students = new HashSet<Student>();
        }

        public System.Guid Type { get; set; }
        public int InternalID { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }

Now, with the whole POCO concept I believe the idea is you can use them as your business objects as well so I planned to add few custom properties and methods to this class. 现在,对于整个POCO概念,我相信您也可以将它们用作您的业务对象,因此我计划向此类添加一些自定义属性和方法。 The way I did this was to extend it in another .cs file since it is a partial class like below 我这样做的方法是将其扩展到另一个.cs文件中,因为它是部分类,如下所示

public partial class School
    {
        public string SchoolState;
        public List<string> SchoolRankings;

        void AddSchoolRanking()
        {
             ...
        }
    }

Now, the following query returned "The entity or complex type 'Student' cannot be constructed in a LINQ to Entities query." 现在,以下查询返回“无法在LINQ to Entities查询中构造实体或复杂类型'Student'”。

List<School> s = new List<School>();
using (SchoolContext ctxt = new SchoolContext())
{
      s = (from a in ctxt.Schools
           where a.InternalID == id
           select new School
           {
              ...

           }).ToList();
}

What is the reason behind this error when the whole point was to be able to use POCO seamlessly in such queries and what would be the right way to get around this ? 当整个问题要能够在此类查询中无缝使用POCO时,此错误背后的原因是什么?解决此问题的正确方法是什么?

Thanks 谢谢

EF will try to map your class's properties to columns in the source data. EF会尝试将您类的属性映射到源数据中的列。

If you extend the class with properties that are not in your data source, you need to tell EF not to try to map them by adding the [NotMapped] attribute: 如果您使用不在数据源中的属性扩展类,则需要通过添加[NotMapped]属性来告诉EF不要尝试映射它们:

public partial class School
{
    [NotMapped]
    public string SchoolState {get; set;}

    [NotMapped]
    public List<string> SchoolRankings;

    void AddSchoolRanking()
    {
         ...
    }
}

You also should not be creating new entities in your EF query, but just let EF do the creation and mapping: 您也不应在EF查询中创建实体,而应让EF进行创建和映射:

  s = (from a in ctxt.Schools
       where a.InternalID == id
       select a).ToList();

You can project EF entities to other non-entity class types, but those instances will have no connection to the context (meaning you can't push changes back to the database). 您可以将EF实体投影到其他非实体类类型,但是这些实例将与上下文无关(这意味着您无法将更改推回数据库)。

Note that I also changed your SchoolState field to a property - public fields are generally discouraged. 请注意,我还将您的SchoolState字段更改为属性-通常不建议使用公共字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM