简体   繁体   中英

Linq query to SQL query

I have a Linq Query that works well but I need to write the SQL Query Can Anybody help me write it? this query will search the database foreach ah and a.HV in the view with the filters of time and model and in the end it checks the option Filter.M that if it is selected it will search for all the data selected in this DropDownCheckBoxes` How can i write the this where and select part in SQL command?

ret1 = (from a in View
        where
            a.LastRefreshTime>=Filter.From && a.LastRefreshTime<=Filter.To && a.ModelCode == mdlCode &&
            Filter.PN.Select(epn => epn.Substring(0, 11)).Contains(a.H) &&
            Filter.PN.Select(epn => epn.Substring(14, 2)).Contains(a.HV)

        select new RData
        {
            v = a.v,
            Date = a.LastRefreshTime,
            UserId = a.UserId,
            M = a.Name,
        }).Distinct().AsQueryable();
ret = ret1.Where(nr =>
    Filter.M == null || !Filter.M.Any() || Filter.M.Contains(nr.M)
).ToList();

Here's a start for you

select a.v v,
       a.LastRefreshTime "Date",
       a.UserId,
       a.Name
  from a
 where a.LastRefreshTime>= arg_filter_from
   and a.LastRefreshTime<= arg_filter_to
   and a.ModelCode = arg_mdlCode
   .
   .
   .

In this query you'll need to replace 'arg_...' with the appropriate values or arguments you want.

Contains is roughly equivalent to "IN" in SQL. For example:

where a.Name in ('jim', 'bob', 'joe')

In can also be used with a subselect which is roughly what I think Filter.PN.Select is doing though I'm not a linq expert. Example:

where a.H in (Select foo from PN_Table)

Or simpler example continuing on the my previous name example:

where a.Name in (select first_name from table)

If we supposed that the Filter.PN list represent a table FilterPN in your sql database, that will be your converted code for the first linq query

  1. select distinct av, a.LastRefreshTime, a.UserId, a.Name
    from [view] a where a.LastRefreshTime>= 'Filter.From' and
    a.LastRefreshTime<='Filter.To' and a.ModelCode = 'mdlCode' and
    exists(select top 1 * from FilterPN where Substring(epn, 1, 11) = aH) and exists(select top 1 * from FilterPN where Substring(e
    select distinct av, a.LastRefreshTime, a.UserId, a.Name
    from [view] a where a.LastRefreshTime>= 'Filter.From' and
    a.LastRefreshTime<='Filter.To' and a.ModelCode = 'mdlCode' and
    exists(select top 1 * from FilterPN where Substring(epn, 1, 11) = aH) and exists(select top 1 * from FilterPN where Substring(e
    enter code here pn, 15, 2) = a.HV)

think to replace the enquoted variables with ur real values 'Filter.To'...

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