问题描述
我是Entity Framework的新手,迄今为止只处理了数据库第一次开发。我一直在阅读实体框架2E,重点是EF4。 EF4中生成的类没有无参数的构造函数,所以我可以在我定义的无参数构造函数中定义部分类并初始化实体属性。其他选项是直接编辑EDMX,并将属性的StoreGeneratedPattern属性设置为Computed或设置属性的Default Value属性。后两个选项的问题是,每当我从模型更新时,它们都将被清除。部分类中的无参数构造函数运行良好,从不被清除。
I am new to Entity Framework and have only worked with database first development so far. I have been reading Entity Framework 2E which focuses on EF4. The generated classes in EF4 had no parameterless constructor so I was able to define partial classes and initialize entity properties in the parameterless constructors I defined there. The other options were to edit the EDMX directly and set the StoreGeneratedPattern attribute of a property to Computed or set the Default Value attribute of the property. The problem with the latter 2 options is that they'd be wiped out whenever I'd Update From Model. The parameterless constructors in partial classes worked nicely and were never wiped out.
现在在EF6中,部分类看起来像POCO,并没有紧密耦合到EntityObject。但是,它们定义了无参数的构造函数。有没有办法设置默认值或初始化对象属性创建时,不会被刷新,当我更新模型?
Now in EF6, the partial classes look like POCOs and are not tightly coupled to EntityObject. However, they define parameterless constructors. Is there a way to set default values or initialize object properties on creation that won't get wiped out when I update the model?
我知道我可以诉诸于在数据源上插入事件处理程序,但我想在全球设置。
I know I can resort to event handlers like Inserting on a data source, but I'd like to just set it globally.
谢谢
推荐答案
我找到了解决方案。编辑模板以在构造函数中输入部分方法定义和调用它,然后在部分类中实现部分方法。
Okay I found the solution. Edit the template to input a partial method definition and a call to it in the constructor, then implement the partial method in a partial class.
完整解释在这里:
这篇关于如何在Entity Framework 6 Database Database中高效地设置默认实体值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!