Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join EF query with dictionary

In global.asax defined and filled Dictionary

public static Dictionary<Guid, string> GlobalUserDictionary;

In controller some logics load data from db via EF DbContext

var db = new DbModel();

var visits = db.Visits.Select(d => new
{
    Id = d.Id,
    UserId = d.UserId,
    User = MvcApplication.GlobalUserDictionary[d.UserId]
});

but controller throw exception:

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String get_Item(System.Guid)' method, and this method cannot be translated into a store expression.

How to join dbcontext model with external data resourse like Dictionary or something similar to it?

like image 272
Ilya Klementiev Avatar asked Jan 18 '26 23:01

Ilya Klementiev


2 Answers

To use the dictionary inside the Select you need to work with Linq to Object instead Linq to Entities. AsEnumerable extension method is going to help you to do that:

    var visits = db.Visits.AsEnumerable().Select(d => new
    {
        Id = d.Id,
        UserId = d.UserId,
        User = MvcApplication.GlobalUserDictionary[d.UserId];
    });

Update

It's true is not a good idea call AsEnumerable without filtering your data first, but after doing that, it could be a good idea call it:

var visits = db.Visits.Select(d => new
{
    d.Id,
    d.UserId
})
.AsEnumerable()
.Select(d => new
{
    Id = d.Id,
    UserId = d.UserId,
    User = MvcApplication.GlobalUserDictionary[d.UserId]
});

The advantage of using AsEnumerable instead ToList is that AsEnumerable does not execute the query until you consult the data, it preserves deferred execution.

like image 121
octavioccl Avatar answered Jan 20 '26 11:01

octavioccl


First select the data from the DB you need, then do a select again to make your full model. Don't use AsEnumerable() on the entire DbSet because you'd retrieve columns that you don't need.

var visits = db.Visits.Select(d => new
{
    d.Id,
    d.UserId
})
.ToList()
.Select(d => new
{
    Id = d.Id,
    UserId = d.UserId,
    User = MvcApplication.GlobalUserDictionary[d.UserId]
});
like image 28
user247702 Avatar answered Jan 20 '26 13:01

user247702



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!