实体框架数据库首先保护构造函数

时间:2014-11-13 14:23:32

标签: c# entity-framework ef-database-first

如何在首次使用实体框架数据库时保护构造函数?

当我从我的数据库生成实体数据模型时,自动生成的类包含一个公共构造函数

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Domain.Models
{
    using System;
    using System.Collections.Generic;

    public partial class MyClass
    {
        public MyClass()
        {

我想要的是受保护的构造函数

    public partial class MyClass
    {
        protected MyClass()
        {

2 个答案:

答案 0 :(得分:3)

您可以通过修改创建模型类的t4模板来完成此操作。在文件顶部附近查找此部分:

foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
    fileManager.StartNewFile(entity.Name + ".cs");
    BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
<#=codeStringGenerator.EntityClassOpening(entity)#>
{
<#
    var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity);
    var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity);
    var complexProperties = typeMapper.GetComplexProperties(entity);

    if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
    {
#>
    public <#=code.Escape(entity)#>()
    {
<#

并用

替换底线public <#=code.Escape(entity)#>()
protected <#=code.Escape(entity)#>()

此更改将为实体类型创建受保护的构造函数。文件中的下部有一个类似的复杂类型构造,您可能也想修改它。

关于“更新”的一句话。如果您从数据库更新模型,则不会覆盖这些更改。但是,如果您更新 EF,修改后的t4模板的问题是,当您想要使用新版本的模板时,必须再次执行此操作。

答案 1 :(得分:1)

您的模型构造函数不正确。 可以根据情况 - 参见Gert提供的链接。 http://msdn.microsoft.com/en-us/library/vstudio/dd468057%28v=vs.100%29.aspx 谢谢Gert的纠正。

所以你可以通过T4改变。

您是否仍然认为这是解决问题的最佳方式?

您可以使用类似验证接口IValidatableObject的内容 EF将在保存操作期间调用以验证数据是否正常。

请记住,在阅读数据时,EF会填充poco实例并在上下文中粘贴引用。 当您填写POCO实例时,您可以在需要时触发验证,ef将在保存之前调用validate。搜索谷歌搜索此主题。

例如

    /// <summary>
    /// Get called everytime  a Validation is triggered on an object. EG MVC model check or  EF save.
    /// </summary>
    public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {

        // Sample Implementation. 
        var validationResult = new List<ValidationResult>();

        // a field cant be null or empty when condition X is true.
        if ( SOME CONDTION that is true   ) {
          validationResult.Add(new ValidationResult(some field is required when...", new List<string>() {"FieldName"}));
          }

        return validationResult;
    }