NPoco icon indicating copy to clipboard operation
NPoco copied to clipboard

NPoco and Datetime Kind

Open shearer3000 opened this issue 3 years ago • 3 comments

Hi

I am using NPoco (4.0.2) in an asp.net core website with Umbraco CMS 9. My poco has a Datetime property and before I insert it into the database I use DateTime.Now() to set the value, which defaults to a datetime Kind of ‘Local’: before

However, when the poco is hydrated back from the database then the Kind is now ‘Utc’ (Did NPoco do this?): after

I used this code to force the Kind back to local/unspecified: .ForEach(x => x.Created = DateTime.SpecifyKind(x.Created, DateTimeKind.Unspecified));

but is there a better convention or simpler way? thanks

shearer3000 avatar Oct 28 '21 04:10 shearer3000

If you're using attribute mapping I guess the following would work:

[Column(ForceToUtc = false)]
public DateTime MyDate {get; set;}

For fluent mapping you can use:

x.Column(y => y.MyDate).ForceToUtc(false);

IIRC you will get DateTimeKind.Unspecified for the returned dates if ForceToUtc is false.

firedog avatar Nov 16 '21 08:11 firedog

thanks firedog - that property decorator worked a treat 😁

shearer3000 avatar Nov 16 '21 20:11 shearer3000

in case it helps anybody, this is how to set ForceToUtc to false for ALL columns on ALL types in your assembly

  var fluentConfig = FluentMappingConfiguration.Scan(scanner =>
      {
          scanner.Assembly(typeof(...a_class_in_your_assembly...).GetTypeInfo().Assembly);
          scanner.Columns.ForceDateTimesToUtcWhere(x => false);
      }
  );

  DbFactory = DatabaseFactory.Config(x =>
  {
      x.UsingDatabase(() => new Database("connString"));
      //didn't seem to be required x.WithMapper(new MyMapper()); // public class MyMapper : DefaultMapper { }
      x.WithFluentConfig(fluentConfig);
  });

  //feed dbfactory into your DI container
  services.AddScoped<NPoco.IDatabase>(x => DbFactory.GetDatabase());

this is also a solve for #443

Beej126 avatar May 30 '22 17:05 Beej126