Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9205847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:03:32+00:00 2026-06-18T00:03:32+00:00

I want a method, annotation or something else that lets me treat a string

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T00:03:33+00:00Added an answer on June 18, 2026 at 12:03 am

    An alternative (and imho preferrable) approach to achieve what you are trying to do is using db.Set<TEntity>().Find(id) etc

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This code isn't localized: Enum.GetNames(typeof(DayOfWeek)) I want a method that returns a list of
I want to write a java annotation which times the method call. something like
I want a method that extracts the data from a JSON-object parsed before as
I only want a method to activate if the pixel that is clicked is
Is there an annotation to declare that a certain method will not be included
I want to know if it is possible to create an Annotation that enforces
I used org.springframework.jmx.export.annotation.@ManagedOperation to expose a method as MBean. I want the operation name
I want to use @PreAuthorize annotation on service methods with Spring Security. One of
I want a method like this: public async void DoSomething() { DoSomethingElse(); } But
I want a method to return an XML Serialized Typed object. Is there an

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.