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

天涯浪子 提交于 2019-11-27 08:05:42

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.

A different approach is to hook into the ObjectMaterialized event in the DbContext and set the kind there.

In my DbContext constructor, i do this:

    ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += new ObjectMaterializedEventHandler(ObjectMaterialized);

and then the method looks like this:

private void ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
        {
            Person person = e.Entity as Person;
            if (person != null) // the entity retrieved was a Person
            {
                if (person.BirthDate.HasValue)
                {
                    person.BirthDate = DateTime.SpecifyKind(person.BirthDate.Value, DateTimeKind.Utc);
                }
                person.LastUpdatedDate = DateTime.SpecifyKind(person.LastUpdatedDate, DateTimeKind.Utc);
                person.EnteredDate = DateTime.SpecifyKind(person.EnteredDate, DateTimeKind.Utc);
            }
        }

The downside is that you need to make sure you set it for each property that you care about but at least it gets set at the lowest possible level.

I used the same approach as Michael only then I dived a little bit deeper, and used reflection to search for DateTime and DateTime?

My solution to ensure that all the DateTime values are readed as Utc DateTimes is as followed:

First I wrote three methods which are in my DbContext Extensions method class. Because I need to use it for multiple DbContexts

public static void ReadAllDateTimeValuesAsUtc(this DbContext context)
{
        ((IObjectContextAdapter)context).ObjectContext.ObjectMaterialized += ReadAllDateTimeValuesAsUtc;
}

private static void ReadAllDateTimeValuesAsUtc(object sender, ObjectMaterializedEventArgs e)
{
    //Extract all DateTime properties of the object type
    var properties = e.Entity.GetType().GetProperties()
        .Where(property => property.PropertyType == typeof (DateTime) ||
                           property.PropertyType == typeof (DateTime?)).ToList();
    //Set all DaetTimeKinds to Utc
    properties.ForEach(property => SpecifyUtcKind(property, e.Entity));
}

private static void SpecifyUtcKind(PropertyInfo property, object value)
{
    //Get the datetime value
    var datetime = property.GetValue(value, null);

    //set DateTimeKind to Utc
    if (property.PropertyType == typeof(DateTime))
    {
        datetime = DateTime.SpecifyKind((DateTime) datetime, DateTimeKind.Utc);
    }
    else if(property.PropertyType == typeof(DateTime?))
    {
        var nullable = (DateTime?) datetime;
        if(!nullable.HasValue) return;
        datetime = (DateTime?)DateTime.SpecifyKind(nullable.Value, DateTimeKind.Utc);
    }
    else
    {
        return;
    }

    //And set the Utc DateTime value
    property.SetValue(value, datetime, null);
}

And then I go to the constructor of my WebsiteReadModelContext which is a DbContext object and call the ReadAllDateTimeValuesAsUtc method

public WebsiteReadModelContext()
{
      this.ReadAllDateTimeValuesAsUtc();
}

I would use the edmx and specify another name for the CreatedOn property (such as CreatedOnInternal). Then set the access modifier for generation to Internal instead of Public. Then you can implement your custom property in the partial class and not worry about this.

Dan Abramov

EF can be pretty nasty sometimes when it comes to stuff it generates.
In Database First applications when I encounter a similar problem I usually follow this approach:

  • Leave autogenerated properties but make them private and change their names;
  • Add public “wrapping” properties that make sense for the business code.

For example, I would rename CreatedOn to something else, like CreatedOnInternal (credits to Jeff) and mark it private in the designer. In the partial class, I would add a public CreatedOn wrapper property that does the conversion back and forth.

I know this is an old question but here is a solution that does not require reflexion or to edit the DbContext for each new property.

It consists of editing the Context.tt:

First add the following using on top of the tt file (around line 40):

using System.Data.Entity.Core.Objects;

Then right under the constructor (around line 86 in my case), add the following generation code:

<#
var entitiesWithDateTime = typeMapper.GetItemsToGenerate<EntityType>(itemCollection)
                                .Where(e => e.Properties.Any(p => typeMapper.GetTypeName(p.TypeUsage) == "System.DateTime"));

if(entitiesWithDateTime.Count() > 0)
{
#>
    private void ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
    {
<#
    var count = 0;
    foreach (var entityType in entitiesWithDateTime)
    {
#>
        <#=count != 0 ? "else " : String.Empty#>if(e.Entity is <#=entityType.Name#>)
        {
            var entity = e.Entity as <#=entityType.Name#>;
<#
            foreach(var property in entityType.Properties.Where(p => typeMapper.GetTypeName(p.TypeUsage) == "System.DateTime"))
            {
#>
            entity.<#=property.Name#> = DateTime.SpecifyKind(entity.<#=property.Name#>, DateTimeKind.Utc);
<#
            }
#>
        }
<#
        count++;
    }
#>
    }
<#
}
#>

This will iterate at compile-time around all the entities of the DbContext and call DateTime.SpecifyKind on each DateTimeProperties.

This code will generate the same code as michael.aird but without requiring manual editing for each new property!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!