【问题标题】:EF 6 Codefirst -Setting default value for a property defined in base class using fluent APIEF 6 Codefirst - 使用流式 API 为基类中定义的属性设置默认值
【发布时间】:2015-09-05 20:23:06
【问题描述】:

我有一个基类,它具有类似的审计属性

public abstract class BaseModel
{
    [Column(Order = 1)] 
    public long Id { get; set; }
    public long CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public long ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
    public bool IsActive { get; set; }
}

我所有的 poco 类都派生自这个类。

我正在尝试为 IsActive 属性设置默认值。我不热衷于使用注释,因此我是否可以使用流利的 API 来处理这个问题。

我试过了,但它不起作用。似乎它创建了一个名为 BaseModel 的新表

modelBuilder.Entity<BaseModel>()
    .Property(p => p.IsActive)
    .HasColumnAnnotation("DefaultValue", true);

任何人都可以在这里提出一种方法吗?

【问题讨论】:

标签: entity-framework entity-framework-6 ef-fluent-api


【解决方案1】:

没有办法做到这一点。它不能使用实体框架设置默认值。相反,您可以使用构造函数

public abstract class BaseModel
{
    protected BaseModel()
    {
        IsActive = true;
    }
}

【讨论】:

    【解决方案2】:

    我通过覆盖 SaveChanges 方法解决了这个问题。请参阅下面的解决方案。

    1. 解决方案说明

      i) 覆盖 DbContext 类中的 SaveChanges 方法。

      public override int SaveChanges()
      {
          return base.SaveChanges();
      }
      

      ii) 编写逻辑来设置默认值

      public override int SaveChanges()
      {
          //set default value for your property
          foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("YOUR_PROPERTY") != null))
          {
              if (entry.State == EntityState.Added)
              {
                  if (entry.Property("YOUR_PROPERTY").CurrentValue == null)
                      entry.Property("YOUR_PROPERTY").CurrentValue = YOUR_DEFAULT_VALUE;
              }
          }
      
          return base.SaveChanges();
      }
      
    2. 示例

      i) 创建基类

        public abstract class BaseModel
        {
             [Column(Order = 1)] 
             public long Id { get; set; }
             public long CreatedBy { get; set; }
             public DateTime CreatedDate { get; set; }
             public long ModifiedBy { get; set; }
             public DateTime ModifiedDate { get; set; }
             public bool IsActive { get; set; }
        }
      

      ii) 覆盖 SaveChanges

      public override int SaveChanges()
      {
      
          //set default value for IsActive property
          foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("IsActive") != null))
          {
              if (entry.State == EntityState.Added)
              {
                  if(entry.Property("IsActive").CurrentValue == null)
                      entry.Property("IsActive").CurrentValue = false;
              }
          }
      
          return base.SaveChanges();
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多