Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9034747
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T08:34:11+00:00 2026-06-16T08:34:11+00:00

I have a ‘model’ which I’m trying to map query results to, but it

  • 0

I have a ‘model’ which I’m trying to map query results to, but it keeps failing for some reason. Here is some more info:

The exception happens here (everything but the select part of the query is different in real life):

var query = @"
        SELECT 
            Id,
            PublicationDate,  
            Title,  
            IntroText,  
            BodyText,  
            IsReadByTarget,
            IsRequired
        FROM Notifications
        WHERE 
            CategoryId = @categoryId
        ";
var parameters = new Dictionary<string, object> {
    { "@categoryId", AppSettings.NotificationCategoryId },
};

var notifications = SqlHelper.GetList<Notification>(_connectionString, query, parameters);

SqlHelper is a small helper class that does all the mapping. Notification is the model I’m mapping to. This is what it looks like:

public class Notification
{
    public string Id { get; set; }

    public Time PublicationDate { get; set; }

    public string Title { get; set; }
    public string IntroText { get; set; }
    public string BodyText { get; set; }

    public string ActiveText
    {
        get
        {
            return string.IsNullOrEmpty(IntroText) ? BodyText : IntroText;
        }
    }

    public Notifiable Target { get; set; }
    public bool IsReadByTarget { get; set; }
    public bool IsRequired { get; set; }
}

Time is also a custom class. It basically holds a date + time (just like datetime but much smaller). It’s only used for communication not for calculations or whatever:

public class Time
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
    public int Hour { get; set; }
    public int Minute { get; set; }
    public int Second { get; set; }

    public Time()
        : this(DateTime.Now)
    {
    }
    public Time(DateTime time)
    {
        Year = time.Year;
        Month = time.Month;
        Day = time.Day;
        Hour = time.Hour;
        Minute = time.Minute;
        Second = time.Second;
    }

    public static implicit operator DateTime(Time time)
    {
        return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
    }
    public static implicit operator Time(DateTime dateTime)
    {
        return new Time(dateTime);
    }
}

So this is also where the magic starts. As you can see, it should silently convert from DateTime to Time and from Time to DateTime. This works fine in normal cases. So doing something like…

Time myTime = DateTime.Now;

…works fine.

But in my case, I get:

Invalid cast from ‘System.DateTime’ to ‘MyNamespace.Time’.

public static List<T> GetList<T>(string connectionString, string query, Dictionary<string, object> parameters) where T : class, new()
{
    var data = new List<T>();

    using (var conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (var command = conn.CreateCommand())
        {
            command.CommandText = query;

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                }
            }

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    var item = Read<T>(reader);
                    data.Add(item);
                }
            }
        }
    }

    return data;
}

public static T Read<T>(SqlDataReader reader) where T : new()
{
    var item = new T();
    var properties = typeof(T).GetProperties();
    foreach (var propertyInfo in properties)
    {
        if (!reader.HasColumn(propertyInfo.Name)) continue;
        var ordinal = reader.GetOrdinal(propertyInfo.Name);

        if (reader.IsDBNull(ordinal)) continue;
        propertyInfo.SetValue(item, Convert.ChangeType(reader[ordinal], propertyInfo.PropertyType), null);
    }

    return item;
}

So basically, it fails when mapping a DateTime column to a Time object while mapping it to a DateTime object works fine.
Any help in why this happens, and a reasonable fix, is appreciated.

I know I can create a new model which uses DateTime instead of Time and map to that and then map that model to the model with Time but that’s not a reasonable fix.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T08:34:12+00:00Added an answer on June 16, 2026 at 8:34 am

    I would suggest creating a custom dictionary of conversions:

    private static readonly Dictionary<Tuple<Type, Type>, Func<object, object>>
        Mappings = new Dictionary<Tuple<Type, Type>, Func<object, object>>
    {
        { Tuple.Create(typeof(DateTime), typeof(Time)), x => (Time)(DateTime) x },
        // Any other conversions...
    };
    

    Then:

    object originalValue = reader[ordinal];
    Func<object, object> converter;
    if (!Mappings.TryGetValue(Tuple.Create(originalValue.GetType(), 
                                           propertyInfo.PropertyType),
                              out converter)
    {
        // Fall back to Convert.ChangeType
        converter = x => Convert.ChangeType(x, propertyInfo.PropertyType);
    }
    object targetValue = converter(originalValue);
    propertyInfo.SetValue(item, targetValue, null);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

have numerous tests working, but my actual test of some objects is failing and
have written this little class, which generates a UUID every time an object of
Have a procedure which looks like Procedure TestProc(TVar1, TVar2 : variant); Begin TVar1 :=
Have deployed numerous report parts which reference the same view however one of them
have a problem. At first look at this HTML <div id=map style=background-image: url(map.png); width:
Have a painfully simple blog Post creator, and I'm trying to check if the
Have an issue with marshall and unmarshall readers and writers. So here it is.
have a nice day. I got problem when trying to create an image from
Have not done this before, so obviously I suck at it. Here 64 pixels
Have created a ATL COM project through which I am inserting Menu Items to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.