在代码优先EF4中更改列名约定

时间:2011-02-06 16:27:51

标签: c# entity-framework-4 code-first

我在CodeFirst中使用EF4。

public class MyContext : DbContext
{    
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
      base.OnModelCreating(modelBuilder);

      modelBuilder.Conventions.Remove<XXX>();
      modelBuilder.Conventions.Add<XXX>());
   }
}

我应该添加或删除哪些约定来使所有数据库标识符(如列名,表名,存储过程等)都是大写(或不带引号)?

Oracle DB中的案例发送(引用)标识符非常糟糕,用户友好。

2 个答案:

答案 0 :(得分:1)

考虑产品和客户类

public class Product {
    public int Id { get; set; }
    public string Name { get; set; }
    public int Stock { get; set; }
}

public class Customer {
    public int Id { get; set; }
    public string Name { get; set; }
}

public class MyDbContext : DbContext {
    public DbSet<Product> Product { get; set; }
    public DbSet<Customer> Customer { get; set; }

    public MyDbContext() { }

    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
        modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
        modelBuilder.Conventions.Add<TableNameUppercaseConvention>();
        base.OnModelCreating(modelBuilder);
    }
}

public class TableNameUppercaseConvention : IConfigurationConvention<Type, EntityTypeConfiguration> {
    public void Apply(Type typeInfo, Func<EntityTypeConfiguration> configuration) {
        configuration().ToTable(typeInfo.Name.ToUpper());
    }
}

修改

我试图做这样的事情,但似乎不起作用,为什么

public class ColumnUppercaseConvention : IConfigurationConvention<MemberInfo, PrimitivePropertyConfiguration> {
    public void Apply(MemberInfo memberInfo, Func<PrimitivePropertyConfiguration> configuration) {
        configuration().ColumnName = memberInfo.Name.ToUpper();
    }
}

我最好的方法是

public class Customer {
    [Column(Name = "ID")]
    public int Id { get; set; }

    [Column(Name = "NAME")]
    public string Name { get; set; }
}
抱歉,我现在无法帮助,但我会继续努力。

答案 1 :(得分:0)

我不知道如何使用约定来执行此操作,但请查看StoreNameAttribute。您可以应用上下文,实体和属性。

Data Annotations in Entity Code First