【问题标题】:Multiple Implementations of an Interface with setting the default values for some variables为某些变量设置默认值的接口的多种实现
【发布时间】:2015-12-22 12:57:48
【问题描述】:

我正在使用 Code first Method 开发 MVC 应用程序。我创建了一个名为 IEntityBase 的通用接口。我已经定义了将在所有表中使用的基本列。我想为某些列分配默认值,以便在创建新行时默认分配这些值。正如我们可以在每个类构造函数中定义 then 一样,但我想将它们分配为泛型,以便将来如果我要添加任何新列,那么我可以这样做。
我可以为此使用 IOC 吗?

例如

public interface IEntityBase
{
    int ID { get; set; }
    bool IsActive { get; set; }
    bool IsDeleted { get; set; }
    DateTime? Created { get; set; }
    string CreatedBy { get; set; }
 }

上面的接口是有5列的接口。我想将默认值分配给 IsActive 为 true,IsDeleted 为 False,Created 为今天的日期。

请帮我解决这个问题。

【问题讨论】:

  • 尝试定义一个基类。
  • 接口定义了一个契约,而不是一个实现。类定义实现。正如@Steven 所说,您需要使用每个事物都继承自的基类。使其抽象化以避免 EF 将其实现为 STI。

标签: c# asp.net-mvc class interface


【解决方案1】:

假设这些是您的 EF POCO 域类,您可以将初始化推送到您的数据库上下文的覆盖 SaveChanges

public class MyCustomDbContext : DbContext
{
    public override int SaveChanges()
    {
        EntityState[] states = 
           new EntityState[] { 
              EntityState.Added, EntityState.Deleted, EntityState.Modified };

        // get all addded/deleted/modified entries
        foreach ( var entry in ChangeTracker.Entries() )
        {
            if ( entry.Entity is IEntityBase &&
                 states.Any( s => s == entry.State )
                )
            {
                IEntityBase e = (IEntityBase)entry.Entity;

                // some properties are always set
                e.ModifiedDate = DateTime.Now;

                // other properties are set only for 
                // entities in specific state
                if ( entry.State == EntityState.Added )
                {
                    e.CreatedDate = DateTime.Now;
                }
            }
        }
        // save changes
        return base.SaveChanges();
    }
 }

【讨论】:

  • 这对于这个特定用例(更新创建/修改日期)实际上是一个很好的解决方案,但应该注意的是,对于在任何其他应用上实现“默认”值来说,这将是一个糟糕的解决方案通用属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
  • 2014-10-01
  • 2021-02-17
  • 2014-03-12
  • 1970-01-01
  • 2018-10-18
相关资源
最近更新 更多