c# - 是否可以防止 Entity Framework 4 覆盖自定义属性?

标签 c# entity-framework entity-framework-4 poco database-first

我首先使用 EF 4 数据库 + POCO。因为 EF 没有简单的方法来声明传入的 DateTimes 是 UTC 类型,所以我将该属性从自动生成的文件移动到另一个文件中的分部类。

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

但是,现在每次我更新模型时,都会在 T4 代中再次创建自动化属性。当然,这会导致以下编译错误:“类型‘Foo’已经包含‘CreatedOn’的定义”。

有什么方法可以告诉 EF 不要生成该属性并让我自己处理它吗?

更新

谢谢大家的回答...

我用不同的名称创建了一个新的自定义属性。

    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;
        }
    }

我还将自动生成的属性的所有 setter 和 getter 设置为 Private,但我需要在 Linq-to-Entities 查询中使用的那些属性除外(叹息)。在这些情况下,我将这些 getter 设置为内部。

我当然希望 DateTime 类型有一个下拉列表来指定 EF 应该将其视为 DateTime 的“种类”。那会节省时间和额外的并发症。

最佳答案

另一种方法是挂接到 DbContext 中的 ObjectMaterialized 事件并在那里设置类型。

在我的 DbContext 构造函数中,我这样做:

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

然后该方法如下所示:

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);
            }
        }

缺点是您需要确保为您关心的每个属性设置它,但至少它设置在尽可能低的级别。

关于c# - 是否可以防止 Entity Framework 4 覆盖自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6931014/

相关文章:

c# - 使用 Async/Await 和 EntityFramework 调用多个存储过程

c# - DbContext 表映射

entity-framework-4 - 在动态 where 子句( Entity Framework )中指定一个以 unicode 命名的列

c# - 传输大文件 : combining streamed transfer and content-length

c# - 如何在我的开发环境中从 Windows 7 x64 上的 C# 连接到 Oracle 数据库

c# - 如何定义多个泛型参数的约束

c# - Winforms 使用状态栏自动调整窗体大小

javascript - 将项目 ID 传递给 JS 函数

c# - 具有业务层和 DAL 的 WPF 体系结构

entity-framework-4 - Entity Framework 中的默认约束