Call a method inside the select part of a LINQ query

c# entity-framework linq-to-entities

Question

I have the following linq query:

var file = (from p in database.tblFile
            join o in database.tblFileVersion on p.fldFileID equals o.fldFileID
            join t in database.tblFileAttachments on p.fldFileID equals t.fldFileID
            where p.fldFileID == team.Key
            where o.fldVersionNo == highestVersion
            select new UserDashboardFile
            {
                Filename = p.fldFilename,
                VersionNumber = o.fldVersionNo,
                FileID = team.Key,
                Type = GetFileType(t.fldTableName),
            }).Single();

GetFileType is a method that returns an enumeration type. There is no syntax error but when I run the project (it is an mvc 4 web project) I receive the following error:

LINQ to Entities does not recognize the method 'DCIS.Code.UserDashboardFileType GetFileType(System.String)' method, and this method cannot be translated into a store expression.

I imagine that this query cannot be translated into a t-sql query but I do not know how to change my query in order to avoid the above error. Thanks in advance...

1
9
11/11/2012 4:28:35 PM

Accepted Answer

You can select anonymous object first and then construct UserDashboardFile.

var file = (from p in database.tblFile
            join o in database.tblFileVersion on p.fldFileID equals o.fldFileID
            join t in database.tblFileAttachments on p.fldFileID equals t.fldFileID
            where p.fldFileID == team.Key
            where o.fldVersionNo == highestVersion
            select new 
            {
                Filename = p.fldFilename,
                VersionNumber = o.fldVersionNo,
                FileID = team.Key,
                FldTableName = t.fldTableName
            }).Single();
var udFile = new UserDashboardFile { ..., Type = GetFileType(file.FldTableName) };

Also you can call .AsEnumerable() before select to prevent GetFileType to be translated in sql.

9
11/11/2012 4:31:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow