James Smithy Cleave
James Smithy Cleave

Reputation: 131

Converting DateTime to String Entity Framework

I have the following code, trying to return d.dateofbirth and d.dateofdeath as strings without much luck.

I have tried using tostring() or convert but both are converted to sql during the runtime so therefore don't work,

I need to be able to show DOB and DOD on 2 lines in the same gridview cell, like this:

DOB DOD

Heres my code so far:

fmsEntities context = new fmsEntities();
var query = from f in context.funerals
            where f.IsPencil == 0
            join d in context.deceaseddetails on f.DeceasedID equals d.ID
            join i in context.funeralservices on f.ID equals i.FuneralID
            where i.IsAlternative == 0
            join h in context.htvalues on f.HtValuesID equals h.ID
            join p in context.placeofdeaths on f.PlaceOfDeathID equals p.ID
            join c in context.coroners on f.CoronerID equals c.ID
            select new DataBindingProjection { DeceasedName = (d.LastName + Environment.NewLine + d.FirstName),
            DOBDOD = Convert.ToString(d.DateOfBirth)};

var dataobjects = query.ToList();

dataGridView1.DataSource = dataobjects;
private class DataBindingProjection
{
    public string DeceasedName {get; set;}
    public string DOBDOD {get; set;}
}

Update, Moved ToList before building the dataProjection as recommended in comments,

fmsEntities context = new fmsEntities();
        var query = (from f in context.funerals
                    where f.IsPencil == 0
                    join d in context.deceaseddetails on f.DeceasedID equals d.ID
                    join i in context.funeralservices on f.ID equals i.FuneralID
                    where i.IsAlternative == 0
                    join h in context.htvalues on f.HtValuesID equals h.ID
                    join p in context.placeofdeaths on f.PlaceOfDeathID equals p.ID
                    join c in context.coroners on f.CoronerID equals c.ID
                    select new { f , d , i , h , p , c }).ToList();

        var dataobjects = query.Select(d => new DataBindingProjection {DeceasedName = (d.LastName + Environment.NewLine + d.FirstName),
                                        DOBDOD = (d.DateOfBirth.ToString() + Environment.NewLine + d.DateOfDeath.ToString())});

        dataGridView1.DataSource = dataobjects;
    }

    private class DataBindingProjection
    {
        public string DeceasedName {get; set;}
        public string DOBDOD {get; set;}
    }

Upvotes: 2

Views: 8290

Answers (1)

Piotr Justyna
Piotr Justyna

Reputation: 4996

James, please consider doing the projection after the "ToList()" is called for the first time, something like this:

var dataobjects = query
.ToList()
.Select(d => new DataBindingProjection { DeceasedName = (d.LastName + Environment.NewLine + d.FirstName),
            DOBDOD = Convert.ToString(d.DateOfBirth)})
.ToList();

Upvotes: 1

Related Questions