简体   繁体   中英

build an Sql query in c#

I need to pass a sql query to c#.

Here is the query:

select 
    T010.A010_nom_ent A010_nom_ent
from
    T010_ENTIDADE T010,
    T016_USUARIO T016
        left outer join
    T307_CELULA_USUARIO T307 ON T307.A306_seq_celula = 0
        and T307.A016_cod_usuario = T016.A016_cod_usuario
where
    T010.A010_cod_entidade = T016.A016_cod_usuario
order by 1

and the code is here:

public List<Entidade> ListarUsuariosCelula()
    {
        List<Entidade> lstEntidades = null;

        try
        {
            oInvitroEntities = new InvitroEntities();

            lstEntidades = (***here is where i want to put the query***)


            return lstEntidades;
        }
        catch (Exception ex)
        {
            LogErro.Trace(ex);
            throw ex;
        }
        finally
        {
            oInvitroEntities = null;
        }
    }

Here is one exemple of what i want to do (i will put just a piece of the code):

try
        {
            oInvitroEntities = new InvitroEntities();

            lstCelula = (from cel in oInvitroEntities.T306_CELULA
                               select new Celula { Codigo = cel.A306_seq_celula, Descricao = cel.A306_dsc_celula }).ToList();


            return lstCelula;
        }

You can use a multi-line string for ease of reading. Assuming you have already setup the database connection and command object, you would need to do something like this for storing your query:

    string query = @"select 
    T010.A010_nom_ent as A010_nom_ent
from
    T010_ENTIDADE T010,
    T016_USUARIO T016
        left outer join
    T307_CELULA_USUARIO T307 ON T307.A306_seq_celula = 0
        T307.A016_cod_usuario = T016.A016_cod_usuario
where
    T010.A010_cod_entidade = T016.A016_cod_usuario
order by 1";

Note, I've corrected your query:

select 
    T010.A010_nom_ent as A010_nom_ent
from
    T010_ENTIDADE T010,
    T016_USUARIO T016
        left outer join
    T307_CELULA_USUARIO T307 ON T307.A306_seq_celula = 0
        T307.A016_cod_usuario = T016.A016_cod_usuario
where
    T010.A010_cod_entidade = T016.A016_cod_usuario
order by 1

If you want to rename a column, you use the as keyword to do so. Aliases are only for referring to tables.

It seems that part with left outer join can be removed (it will not change result of query). So you sql query can be reqrite in linq to entities (there is single inner join cause i droped off your left outer join):

oInvitroEntities.T010_ENTIDADE.Join(oInvitroEntities.T016_USUARIO,
                                    t10=>t10.A010_cod_entidade, 
                                    t16=>t16.A016_cod_usuario, 
                                    (t10, t16) => t10.A010_nom_ent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM