0
votes

I am using EF5 and using their code generator I got the POCO classes generated. 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. The way I did this was to extend it in another .cs file since it is a partial class like below

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."

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 ?

Thanks

1

1 Answers

1
votes

EF will try to map your class's properties to columns in the source data.

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:

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:

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

Note that I also changed your SchoolState field to a property - public fields are generally discouraged.