ɐsɹǝʌ ǝɔıʌ
ɐsɹǝʌ ǝɔıʌ

Reputation: 4512

How to create a list of child IDs

In my controller I have a method that receives a decimal value (id). The objective of this method is to recover a list of old revisions from a database table containing work permits. Each record on this table has a WorkPermitID as a primary key and OldRevisionWorkPermitID referencing the ID of the previous version.

I have no problems when collecting the children IDs (old versions), but it raises an exception indicating that LINQ to Entities does not recognize .ToString() method.

What I'm doing wrong? I know that I need to do without converting to string (WorkPermitID is defined as numeric in the database), but I tried several ways with no success.

public ActionResult GetVersions(decimal id){


                    var model = new PermisosTrabajoModel();

                    List<string> ChildIDs = new List<string>();

                    var WP = OtWeb.WorkPermit.Single(q => q.WorkPermitID == id);

                    while (WP.OldRevisionWorkPermitID != null)
                    {
                        var child = WP.OldRevisionWorkPermitID;
                        ChildIDs.Add(child.ToString());
                        WP = OtWeb.WorkPermit.Single(q => q.WorkPermitID == child);
                    }


                    model.WPs = OtWeb.WorkPermit
                                .Where(q => q.DeptID == 1
                                && ChildIDs.Contains(q.WorkPermitID.ToString())).ToList();

return View (model);
}

Upvotes: 0

Views: 98

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

Solution1

If both of your fields are decimal... Don't use ToString(), and use a list of decimal

var model = new PermisosTrabajoModel();

var childIDs = new List<decimal>();

var WP = OtWeb.WorkPermit.Single(q => q.WorkPermitID == id);

while (WP.OldRevisionWorkPermitID != null)
     {
         childIDs.Add(WP.OldRevisionWorkPermitID);
         WP = OtWeb.WorkPermit.Single(q => q.WorkPermitID == child);
     }
model.WPs = OtWeb.WorkPermit
                .Where(q => q.DeptID == 1
                       && childIDs.Contains(q.WorkPermitID)).ToList();

Solution2

In linq2entities, you can use SqlFunctions.StringConvert instead of ToString() for a numeric value.

SqlFunctions.StringConvert(q.WorkPermitId)

instead of

q.WorkPermitID.ToString()

for example

Upvotes: 1

Related Questions