schotime / NPoco

Simple microORM that maps the results of a query onto a POCO object. Project based on Schotime's branch of PetaPoco
Apache License 2.0
846 stars 301 forks source link

NPoco and Datetime Kind #648

Open shearer3000 opened 2 years ago

shearer3000 commented 2 years ago

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

firedog commented 2 years ago

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.

shearer3000 commented 2 years ago

thanks firedog - that property decorator worked a treat 😁

Beej126 commented 2 years ago

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