0

I have a query that retrieves three columns from a table - ID, EMAIL_ID_NUMBER, and MESSAGE_SUBJECT. I want to map these three columns to the properties of an object ID, EMAIL_ID_NUMBER and MessageSubject (The names are chosen to highlight the issue). The problem is that the mapping does not work as I expect.

I expect that when I specify Column(Name = "COLUMN1") next to some property, then the value of the COLUMN1 will be stored into this property. However, it does not work. The value is stored only when the property name is exactly the same as the column name. For example in this case...

[Column(Name = "MESSAGE_SUBJECT")]
public String MessageSubject;

... I expect that the MESSAGE_SUBJECT column from the query will populate the MessageSubject property. However, it is not happening. The question is how can I do this?

Other properties are populated without issues as their names are the same as the names of the columns in the query.

The code is below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Text;
using System.Threading.Tasks;

namespace LinqExample1
{

  class Record1
  {
    [Column(CanBeNull = false, IsPrimaryKey = true)]
    public int ID;

    [Column()]
    public String EMAIL_ID_NUMBER;

    [Column(Name = "MESSAGE_SUBJECT")]
    public String MessageSubject;

    public override string ToString()
    {
      return $"{base.ToString()}. ID={ID}. Name={EMAIL_ID_NUMBER}. MessageSubject={MessageSubject}";
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      var context = new DataContext(System.Configuration.ConfigurationManager.ConnectionStrings["LinqExample1.Properties.Settings.MyConnectionString"].ToString());
      var emailTemplates = context.ExecuteQuery<Record1>("select ID, EMAIL_ID_NUMBER, MESSAGE_SUBJECT from EMAIL_NOTIFICATIONS");
      foreach (Record1 emailTemplate in emailTemplates)
      {
        Console.WriteLine(emailTemplate.ToString());
      }
    }
  }
}

The output that I get looks like below:

LinqExample1.Record1. ID=4. Name=EM 05. MessageSubject=
LinqExample1.Record1. ID=16. Name=EM 06. MessageSubject=
LinqExample1.Record1. ID=17. Name=EM 07. MessageSubject=

E.g. MessageSubject is always empty even if the underlying query returns data for the MESSAGE_SUBJECT column.

There is a couple of potential solutions which I don't like.

  1. Make property names same as column names. E.g. the Record1 class will have properties ID, EMAIL_ID_NUMBER, and MESSAGE_SUBJECT.
  2. Use column aliases in the query to match property names. E.g. use query "select ID, EMAIL_ID_NUMBER Name, MESSAGE_SUBJECT MessageSubject from EMAIL_NOTIFICATIONS" and the Record1 property names ID, Name, and MessageSubject.
Andrew
  • 61
  • 3

0 Answers0