It is possible to end up duplicating the same logic in the manner of the dreaded copy-modify monster. I have learned to take it seriously when I find myself doing this because it has never not eventually come back to haunt me .
The key to making this work is to first deploy a couple of simple extension methods to make reflection a bit easier.
Then it is less daunting of a task to write a generic routine that acts on any entity set with common propertie(s).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ObjectSetExtensions | |
{ | |
public static int IdByName<T>(this ObjectSet<T> set, string name) where T : class | |
{ | |
int id = set.ToList() | |
.Where(c => c.MemberValue<string>("name") == name) | |
.Select(c => c.MemberValue<int>("id")) | |
.FirstOrDefault(); | |
if (id != default(int)) | |
{ | |
return id; | |
} | |
else | |
{ | |
throw new Exception(string.Format("The {0} named {0} does not exist.", typeof(T).Name, name)); | |
} | |
} | |
} |