Search code examples
c#entity-frameworkforeign-keysentity-relationship

ForeignKey String ToLower Entity Framework


I have a problem with the ForeignKey, as you will see in the database table i have the following value "LA URBINA" in the column "EQU". in my model the property is:

[ForeignKey("Equipo")]
public string EQU { get; set; }

private Equipo equipo;
public virtual Equipo Equipo
{
    get { return equipo; }
    set { equipo = value; }
}

the problem is that in the table "Equipo" the key code is "La Urbina" not "LA URBINA" and therefore does not make the relationship, any idea to make the comparison regardless if the value is lower or upper? please excuse my bad English, I hope you understand me and you can help me


Solution

  • just in case this can help someone my solution was

    in the model:

    private string equ;
    [ForeignKey("Equipo")]
    public string EQU
    {
        get { return equ.Capitalize(); }
        set { equ = value; }
    }
    
    private Equipo equipo;
    public virtual Equipo Equipo
    {
        get { return equipo; }
        set { equipo = value; }
    }
    
    public static string Capitalize(this string str)
    {
        if (str != null || str == "")
        {
            str = str.ToLower();
            str = Regex.Replace(str, @"\b[a-z]", delegate(Match m)
            {
                return m.Value.ToUpper();
            });
        }
        return str;
    }
    

    in the class Equipo:

    private string codigo;
    [Key]
    [StringLength(20)]
    public string Codigo
    {
        get { return codigo.Capitalize(); }
        set { codigo = value; }
    }