1

我知道您可以通过使用定义每个类的实体架构名称,ToTable("TableName", "SchemaName")但是有没有办法设置它,以便您可以为配置中的所有表设置架构名称,因为当我使用某些类型的关系时,我会得到一些奇怪的结果映射和拆分实体映射,它dbo.TableName在内部 sql 查询中恢复为默认值

有关 sql 输出示例,请参阅此较早的帖子

4

2 回答 2

3

我在 EF 4.1 中拥有 Oracle 数据库优先,所有映射都使用数据注释完成。测试和生产环境中的不同模式名称。我的解决方案是在 OnModelCreating 期间借助流畅的 API、反射和后期绑定动态映射 Schema。遍历泛型类型的所有 Context 类属性并完成繁琐的工作。到目前为止为我工作。

public class Context : DbContext
{
    public Context()
        : base(new OracleConnection(ConfigurationManager.ConnectionStrings["OraAspNetConString"].ConnectionString), true)
    {
    }

    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        foreach (var p in typeof(Context).GetProperties().Where(foo=>foo.PropertyType.IsGenericType))
        {
            // this is what we are trying to accomplish here -- 
            //modelBuilder.Entity<User>().ToTable("TBL_USERS", "TestSchema");

            Type tParam = p.PropertyType.GetGenericArguments()[0]; // typeof User
            MethodInfo generic = typeof(DbModelBuilder).GetMethod("Entity").MakeGenericMethod(new[] { tParam });
            object entityTypeConfig = generic.Invoke(modelBuilder, null);

            MethodInfo methodToTable = typeof(EntityTypeConfiguration<>).MakeGenericType(new[] { tParam }).GetMethod("ToTable", new Type[] { typeof(string), typeof(string) });
            methodToTable.Invoke(entityTypeConfig, new[] { GetMappedTableName(tParam), currentOraSchemaName });
        }

        base.OnModelCreating(modelBuilder);
    }

    private string currentOraSchemaName = ConfigurationManager.AppSettings.Get("OraSchemaName");

    private string GetMappedTableName(Type tParam)
    {
        TableAttribute tableAttribute = (TableAttribute)tParam.GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault();
        return tableAttribute.Name;
    }
}

这里的用户类,没有硬编码的模式映射——

[Table("TBL_USERS")]
public class User
{
    [Column("USER_ID")]
    public string UserId { get; set; }

    [Column("USER_NAME")]
    public string Name { get; set; }} 
于 2012-01-18T04:32:54.433 回答
0

由于最终的 EFv4.1 版本没有用于自定义约定的公共 API,因此您无法从 API 全局更改架构。

于 2011-07-21T07:13:24.543 回答