Linq to Entities in EF4 Using Generated POCO Classes

I used the ADO.NET C # POCO Entity Generator Visual Studio add-in to create POCO classes for my objects.

When I try to use a class in a Linq to Entities query, for example, below:

var q = from w in entities.Widgets
        select new Widget
        {
            Id = w.Id,
            WidgetName = w.WidgetName,
            WidgetDescription = w.WidgetDescription
        };


return q.ToList();

I get the following exception:

"The object or complex type MyNamespace.Widget 'cannot be constructed in a LINQ to Entities query.

The only way around this is to use an anonymous type and then another LINQ query:

var q = from w in entities.Widgets
        select new
        {
            Id = w.Id,
            WidgetName = w.WidgetName,
            WidgetDescription = w.WidgetDescription
        };

var r = from e in q.AsEnumerable()
        select new Widget
        {
            Id = e.Id,
            WidgetName = e.WidgetName,
            WidgetDescription = e.WidgetDescription
        };

return r.ToList();

This works, but is pretty redundant. I understand why I get an exception, but is there a more elegant way around this?

The fact that POCO classes are generated by the Entity Entity Generator ADO.NET C # generator does not seem to be related to the problem; I tried using my own POCO classes and saw the same exception.

.

EDIT: ​​ ADO.NET # POCO Entity Generator Visual Studio - http://blogs.msdn.com/b/adonet/archive/2010/01/25/walkthrough-poco-template-for-the-entity-framework.aspx

+3
2

, MyNamespace.Widget - , EDM?

, LINQ-Entities . , POCO .

, .

, :

var widgets = entities
               .Widgets
               .ToList() // materialize query
               .Select(x => new Widget
                       {
                          Id = w.Id,
                          WidgetName = w.WidgetName,
                          WidgetDescription = w.WidgetDescription
                       }
               ).ToList();

, .

: "" EDM?

POCO , . , (POCO), ( , ) . POCO DTO N-?

+4

, Entity Entity Framework, , -, . , , .

, , , , w , View, Widget. , , :)

+2

Source: https://habr.com/ru/post/1781547/


All Articles