Search code examples
c#linq-to-entities

Using Linq query when we get record by id how can i assign that value to another column?


Here I wrote simple where condition linq query I'm getting data from the database, but I want to assign that data to another column.

Employee

public class Employee
{
        public string Id{ get; set; }
        public string Name{ get; set; }
        public string Email{ get; set; }
}

Linq query:

public Employee GetEnqDetails(int EnqId)
{
    if (EnqId != null)
    {
        var x = from n in db.Employee 
                where n.Id == EnqId
                select n;
        return x.FirstOrDefault();
    }
    else
    {
        return null;
    }
}

Here from Employee table whatever data I'm getting I want to assign that data to another class as

public class EmailContent
{
        public string Subject { get; set; }
        public string Body { get; set; }
}

Here subject =x.Name +"" x.Email How can i assign that value


Solution

  • So you are getting the Employee details from the method GetEnqDetails() you can create a new instance of the EmailContent with those details:

    var employ = GetEnqDetails(101);
    if (employ != null)
    {
        EmailContent emc = new EmailContent() { Subject = String.Format("{0} {1}", employ.Name, employ.Email), Body = "" }; 
        // proceed with emc 
    }
    

    If you don't want to use the filtered employee details, only the requirement is to instantiate the EmailContent with the employee details means you can change the method like the following:

    public static EmailContent GetEnqDetails(string EnqId)
    {
        if (EnqId != null)
        {
            return db.Employee.Where(n => n.Id == EnqId)
                              .Select(x => new EmailContent()
                              {
                                  Subject = String.Format("{0} {1}",
                                  x.Name, x.Email),
                                  Body = ""
                              }).FirstOrDefault();
        }
        else
        {
            return null;
        }
    }
    

    Update as per the comment:

    There is a DataType mismatch as specified in the comment, that is EnqId is int and n.Id is string. Please correct them accordingly. I just changed the parameter as string in my code. Because the comparison (if (EnqId != null)) is meaning less in the value is integer. So if you are forwarding with int remove the condition