EF 6 Codefirst-使用流畅的API为基类中定义的属性设置默认值

问题描述 投票:2回答:2

我有一个具有审计属性的基类,例如

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
2个回答
5
投票

无法执行此操作。它不能使用Entity Framework设置默认值。相反,您可以使用构造函数

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

0
投票

我已经通过覆盖 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();
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.