Set extended property via Linq-to-entity

I want to get the data and set the property that was added to the entityobject (via a partial class) on the fly.

How can i do this?

this is my request:

var ret = (from item in contex.Items
               select new Itemm
               {   
                  Title = item.Title,
                  Count = 1 // more complex: Count =item.refToAnotherEntity.Count()                                          
               });

public partial class Itemm 
{
     public int Count { get; set; }
}

I get an error: An entity or complex type cannot be constructed in a LINQ to Entities query

+3
source share
4 answers

The problem is that Linq to Entities is trying to convert the entire expression to SQL. This is not entirely possible with your β€œnew” statement.

Try the following:

var ret = (from item in contex.Items
           select new Itemm
           ).ToList();
ret = (from item in ret
       select new Itemm
           {   
              Title = item.Title,
              Count = 1                                           
           }).ToList();

Basically, you will make sure that the results are returned from the SQL server (ToList () does this) before trying to rebuild them. This is ugly, and you might clean it up a bit, but the code above should work.

0

, SQL, linq , .

.

OnCreated()  {}

, ,

protected override void OnLoaded (bool initial)  {      base.OnLoaded();  }

0

. Wrapper , Count, . :

public class ItemWithCount
{
   public Item Item { get; set; }
   public int Count
   {
        get { return Item.Count; }
        set { Item.Count = value; }
   }
}

:

var ret = (from item in contex.Items
           select new ItemWithCount
           {   
              Item = item,
              Count = item.refToAnotherEntity.Count()                                          
           }).AsEnumerable().Select(x => x.Item);

2 , , Count . - :

var ret = (from item in contex.Items
           select new
           {   
              Item = item,
              Count = item.refToAnotherEntity.Count()                                          
           });
Parallel.ForEach(ret, x => x.Item.Count = x.Count);
var results = ret.Select(x => x.Item);

, althouth , ... ?

0

(.. IQueryable<T> IEnumerable<T>), - :

var query = (from item in context.Items
    select new Item {                     
        Title = item.Title
    });

var ret = query.AsEnumerable().Select(i => {
    // Set the count.
    i.Count = 1;

    // Return the item.
    return i;
});

IEnumerable<T>, LINQ LINQ to Objects, .

-1

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


All Articles