将dbset作为参数传递给函数

时间:2014-12-29 21:23:15

标签: c# ef-code-first entity

我无法找到我正在寻找通过堆栈搜索的答案,所以我发布了这个。

鉴于此背景

  public ProjectionsContext()
        : base("name=ProjectionsDatabase")
    {
    }

    public virtual DbSet<Projection> Projections { get; set; }

    public virtual DbSet<Symbol> Symbols { get; set; }

    public virtual DbSet<TradePriceData> TradePriceDatas { get; set; }

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        **//set all decimal properties in Projection Entity to be Required
        var decimalproperties = typeof(Projection).GetProperties()
                                  .Where(p => p.PropertyType == typeof(decimal));
        foreach (var property in decimalproperties)
        {
            var lambda = CreateLambdaExpression<Projection, decimal>(property);
            modelBuilder.Entity<Projection>()
                .Property(lambda)
                .IsRequired();
        }**

        //add the custom configurations for each entity
        modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());

    }
}

我想重构粗体代码,这显然不是那么困难,但我似乎无法弄清楚如何传入实体(上例中的投影),所以我可以传入任何设置属性的实体。

喜欢的东西;

private static void SetEntityPropertiesRequired<TEntity>(
                        DbModelBuilder modelBuilder,
                        TEntity entity)
    {
        //set all decimal properties in Projection Entity to be Required
        var decimalproperties = typeof (entity).GetProperties()
            .Where(p => p.PropertyType == typeof (decimal));

        foreach (var property in decimalproperties)
        {
            var lambda = BuildLambda<entity, decimal>(property);
            modelBuilder.Entity<entity>()
                .Property(lambda)
                .IsRequired();
        }
    }

并像这样调用它;

 SetEntityPropertiesRequired<Projection>(modelBuilder);

产生错误,方法需要两个参数。

更新

答案,根据SLaks总的回答是:

  private static void SetEntityPropertiesDecimalTypeToRequired<TEntity>(
                        DbModelBuilder modelBuilder) where TEntity : class
    {
        //set all decimal properties in Projection Entity to be Required
        var decimalproperties = typeof(TEntity).GetProperties()
            .Where(p => p.PropertyType == typeof(decimal));

        foreach (var property in decimalproperties)
        {
            var lambda = BuildLambda<TEntity, decimal>(property);
            modelBuilder.Entity<TEntity>()
                .Property(lambda)
                .IsRequired();
        }
    }

这样称呼;

SetEntityPropertiesDecimalTypeToRequired<Projection>(modelBuilder);

一个很好的奖励是能够传递属性类型(decimal,int,string等)!任何人都想尝试一下,因为所有类型都不相同,有些是结构,有些是类

1 个答案:

答案 0 :(得分:0)

您正在寻找通用方法:

private static void SetEntityPropertiesRequired<TEntity>(DbModelBuilder modelBuilder)
{
    //set all decimal properties in Projection Entity to be Required
    var decimalproperties = typeof (TEntity).GetProperties()
    ...