代码之家  ›  专栏  ›  技术社区  ›  Emil Badh

亚音速3和MySQL,在CleanUp()方法中从列名中删除下划线会导致在linq查询中使用属性时出现异常

  •  0
  • Emil Badh  · 技术社区  · 15 年前

    我在MySQL中使用亚音速3(.0.0.3)ActiveRecord时遇到了一个问题。

    由于MySQL不允许在表名或列名中使用大写字母(如果使用,则忽略它),我决定使用下划线分隔单词,例如entity_id,然后使用CleanUp()方法添加标题大小写并删除下划线。
    一位朋友编写了一个ToTitleCase(string s)方法,如下所示:

    string ToTitleCase(string s)
    {
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;
        return textInfo.ToTitleCase(s);
    }
    

    string CleanUp(string tableName){
        string result=tableName;
    
        //strip blanks
        result=result.Replace(" ","");
    
        //put your logic here...
        result = ToTitleCase(result);
        result = result.Replace("_", "");
    
        return result;
    }
    

    如果我这样做:

    var entity = Entity.All().Where(e => e.EntityName.Contains("John"));
    

    如果我删除

    result = result.Replace("_", "");
    

    一切都很好,只是我得到的属性看起来像实体_Id,这不是我想要的。

    如果有人知道为什么会这样,我很想听听。如果可以修复,那就更好了!这不是闹剧,但有点烦人。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Nosynchro    14 年前

    在很多个月的时间里,这对我来说都是一个问题,在任何受支持的DB上使用亚音速时,我都避免使用下划线。直到昨天,我还不得不支持一个在SQLServer数据库中有下划线的遗留项目。

    您必须在SubSonic.Core(文件:SubSonic.Core\Schema\DatabaseTable.cs)的源代码中修复它:

    查找此方法:

    public IColumn GetColumnByPropertyName(string PropertyName)
    {
        return Columns.SingleOrDefault(x => x.Name.Equals(PropertyName, StringComparison.InvariantCultureIgnoreCase));
    }
    

    并将其更改为:

    public IColumn GetColumnByPropertyName(string PropertyName)
    {
        return Columns.SingleOrDefault(x => x.PropertyName.Equals(PropertyName, StringComparison.InvariantCultureIgnoreCase));
    }
    

    Structs.tt

    请在顶部附近找到:

    Columns.Add(new DatabaseColumn("<#=col.Name#>", this)
    {
        IsPrimaryKey = <#=col.IsPK.ToString().ToLower()#>,
        DataType = DbType.<#=col.DbType.ToString()#>,
        IsNullable = <#=col.IsNullable.ToString().ToLower()#>,
        AutoIncrement = <#=col.AutoIncrement.ToString().ToLower()#>,
        IsForeignKey = <#=col.IsForeignKey.ToString().ToLower()#>,
        MaxLength = <#=col.MaxLength#>
    });
    

    并添加以下行:

        PropertyName = "<#=col.CleanName#>",
    

    使其成为:

    Columns.Add(new DatabaseColumn("<#=col.Name#>", this)
    {
        PropertyName = "<#=col.CleanName#>",
        IsPrimaryKey = <#=col.IsPK.ToString().ToLower()#>,
        DataType = DbType.<#=col.DbType.ToString()#>,
        IsNullable = <#=col.IsNullable.ToString().ToLower()#>,
        AutoIncrement = <#=col.AutoIncrement.ToString().ToLower()#>,
        IsForeignKey = <#=col.IsForeignKey.ToString().ToLower()#>,
        MaxLength = <#=col.MaxLength#>
    });
    

    问题是,一旦清除了列名,亚音速将通过匹配亚音速生成的列来尝试在查询中查找有效列 列名

    这些变化将确保亚音速与清洁的空气相匹配 属性名

    推荐文章