NPoco
NPoco copied to clipboard
NPoco and Datetime Kind
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’:
However, when the poco is hydrated back from the database then the Kind is now ‘Utc’ (Did NPoco do this?):
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
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.
thanks firedog - that property decorator worked a treat 😁
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