vendredi 10 novembre 2017

How to standardize generic Entity Framework C# code using reflection or generics?

I have three database tables which represent comparison scores for common name strings. They're separated into individual tables to speed scanning time. All of them share the same basic structure of four columns: an ID, two strings and score represtning how different the strings are.

The DB is accessed via Entity Framework. In the implementation code, this leads me to having three near-identitical functions, one for each object type:

    private bool CheckSurnameJw(string string1, string string2, double threshold)
    {
        JwDistanceSurname jw = _rep.GetJwDistanceSurname(string1, string2);

        if (jw == null)
        {
            double dist = JaroWinklerProximity(string1, string2);
            JwDistanceSurname newJw = new JwDistanceSurname { Surname1 = string1, Surname2 = string2, JwScore = dist };
            _rep.Update(newJw);
            _rep.SaveChanges();

            return dist >= surnameProximityThreshold;
        }
        else
        {
            return jw.JwScore >= threshold;
        }
    }

Looking at this, while I could nip and tuck slightly, I can't see any clear areas where the function could be sensibly improved by farming code out to another function. But it annoys the hell out of me to have to re-implement the same logic block three times, to deal with three different identity types.

I wrapped all three classes in an interface specifiying the four columns to see if that would help me tidy things up. But it doesn't: I can't use a generic "get" function because each is querying a different table and, likewise, when I create a new instance of the class I need to give it the appropriate type.

Is there a way I can improve this using reflection/generics?





Aucun commentaire:

Enregistrer un commentaire