Write linq query results to .csv file mvc

时间:2016-07-11 21:57:43

标签: c# asp.net-mvc linq

im trying to write a linq query that searches stuff in the database. if it gets the data it should return the results to a .csv file. this is my query

var query = from a in db.User where a.id.Equals(table.id)
            select a;

im struggling to find how i can use this query to write results to database. im using c# mvc

Update

Right now this is my method:

public FileContentResult ConnectToDatabase(Requests uc)
    {
        Context db = new Context();
        var query = (from a in db.Request
                     where a.Idnumber.Equals(uc.Idnumber)
                     select a);

        string csv = string.Concat(from re in query
                                  select string.Format("{0},{1},{2}\n", re.Idnumber, re.RequestStartDate, re.RequestEndDate));


        return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report.csv");

    }

and i am getting a this error: "LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)"

1 个答案:

答案 0 :(得分:1)

the problem here is that query is an IQueryable, so when you do select string.Format("{0},{1},{2}\n ... Entity Framework will try to convert that to SQL and it won't be able to.

So there are a few ways you can solve this:

1) Keep the IQueryable but build the CSV rows in a way that EF can translate to SQL:

var csv = string.Concat(query.Select(re => re.IdNumber + "," + re.RequestStartDate + "," + re.RequestEndDate + "\n));

2) Materialize query into a List so that the string.Format call is done in C#, not SQL.

var query = (from a in db.Request
                     where a.Idnumber.Equals(uc.Idnumber)
                     select a).ToList();