I want a method, annotation or something else that lets me treat a string as C# code.
I read about CodeDom, Reflection and T4 templates but that isn't what I'm looking for.
What I need is more simple, I hope. I don´t want code generated at run-time.
Here's an example to clarify what I want. I'm using VS2010, Entity Framework 5 and the Code First approach.
I have an Insert method for each entity type. The following is the code for the method to insert a Cliente
(Costumer). If a Cliente
exists in the database then its updated instead of inserted:
public int InsertarCliente(Cliente cliente)
{
int id = cliente.ClienteId;
try
{
if (id != -1)
{
var clt = db.Clientes.Find(id);
clt.Nombre = cliente.Nombre;
clt.Apellido1 = cliente.Apellido1;
clt.Apellido2 = cliente.Apellido2;
// more similar statements
}
else
db.Clientes.Add(cliente);
db.SaveChanges();
return cliente.ClienteId;
}
catch (DbEntityValidationException exc)
{
// code
}
}
I was trying to use CodeDom to create a generic method that works for any entity type. The method doesn't work and I know why: CodeDom doesn't compile and run arbitrary code, it requires extra namespaces, using statements, classes, methods, etc. That method doesn't work, here is the code to clarify what I was trying to do:
public int Insertar<TEntity>(TEntity entidad, string[] atributos)
where TEntity : class
{
string nombreEntidad = entidad.GetType().Name;
string entidadId = nombreEntidad + "Id";
string tabla = nombreEntidad + "s";
int id = Convert.ToInt32(
entidad.GetType().GetProperty(entidadId).GetValue(entidad, null));
try
{
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
CompilerResults cr;
string codigo;
if (id != -1)
{
codigo = "var entidadAlmacenada = db." + tabla + ".Find(id);";
cr = codeProvider.CompileAssemblyFromSource(cp, codigo);
CompilerResults cr2;
string codigoActualizador;
foreach (string atr in atributos)
{
codigoActualizador =
"entidadAlmacenada." + atr + " = entidad." + atr + ";";
cr2 = codeProvider.CompileAssemblyFromSource(
cp, codigoActualizador);
}
}
else
{
codigo = "db." + tabla + ".Add(entidad);";
cr = codeProvider.CompileAssemblyFromSource(cp, codigo);
}
db.SaveChanges();
return Convert.ToInt32(
entidad.GetType().GetProperty(entidadId).GetValue(entidad, null));
}
catch (DbEntityValidationException exc)
{
// code
}
}
I want a way to convert (inline) a string that represents code to the code that it represents.
Something like:
string code = "line of code";
code.toCode(); // or
toCode(code); // or
[ToCode]
code;
Sorry if I'm writing too much, but I want to be clear this time.
What I need is that a string "containing code" to be replaced by the code before compilation time. No run-time compilation or execution.
Is there a way to do something like that?
TIA
EDIT:
The above example was just an example. But I want the "string to code conversion" in any situation.