Search code examples
c#entity-frameworkentity-framework-4pocodatabase-first

Is it possible to prevent EntityFramework 4 from overwriting customized properties?


I am using EF 4 Database first + POCOs. Because EF has no easy way to state that incoming DateTimes are of kind UTC, I moved the property from the auto-generated file to a partial class in another file.

    private DateTime _createdOn;
    public virtual System.DateTime CreatedOn
    {
        get { return _createdOn; }
        set
        {
            _createdOn =
                (value.Kind == DateTimeKind.Unspecified)
                    ? _createdOn = DateTime.SpecifyKind(value, DateTimeKind.Utc)
                    : value;
        }
    }

However, now every time I update the model, the automated properties get created again in the T4-generation. Of course this causes the following compilation error: "The type 'Foo' already contains a definition for 'CreatedOn'".

Is there any way to tell EF to not generate that property and to let me handle it on my own?

Update

Thanks for everyone's answers...

I created a new custom property with a different name.

    public virtual System.DateTime CreatedOnUtc
    {
        get
        {
            return (CreatedOn.Kind==DateTimeKind.Unspecified)
                ? DateTime.SpecifyKind(CreatedOn, DateTimeKind.Utc)
                : CreatedOn;
        }
        set
        {
            CreatedOn =
                (value.Kind == DateTimeKind.Unspecified)
                    ? CreatedOn = DateTime.SpecifyKind(value, DateTimeKind.Utc)
                    : value;
        }
    }

I also set all of the setters and getters of the auto-generated property to Private with the exception of those properties that I needed to use in a Linq-to-Entities query (sigh). In those cases, I set those getters to internal.

I sure wish there was a dropdown on DateTime types to specify what "Kind" of DateTime that EF should treat it as. That would have saved hours and the extra complication.


Solution

  • I think things start to get messy if you try to manually modify EF generated classes.

    There are two options that I'd suggest pursuing:

    1. Don't modify the existing property, but add a new one to your partial class, CreatedOnUTC or something similar.
    2. Modify the T4 template to alter the way that it generates the accessors for these date properties (easier if every DateTime property is to work the same way). It won't be trivial, since it's type dependent, but would at least allow you to use the generator in future.