Programming

Linq에서 SQL Like %를 수행하는 방법은 무엇입니까?

procodes 2020. 2. 26. 22:47
반응형

Linq에서 SQL Like %를 수행하는 방법은 무엇입니까?


Linq로 전환하려고하는 SQL 절차가 있습니다.

SELECT O.Id, O.Name as Organization
FROM Organizations O
JOIN OrganizationsHierarchy OH ON O.Id=OH.OrganizationsId
where OH.Hierarchy like '%/12/%'

내가 가장 우려하는 라인은 다음과 같습니다.

where OH.Hierarchy like '%/12/%'

예를 들어 / 1 / 3 / 12 /와 같은 계층 구조를 저장하는 열이 있으므로 검색하려면 % / 12 / %를 사용하십시오.

내 질문은 Linq 또는 .NET이 백분율 기호를 사용하는 것과 동등한 것입니까?


.Where(oh => oh.Hierarchy.Contains("/12/"))

당신은 또한 사용할 수 있습니다 .StartsWith()또는 .EndsWith().


이것을 사용하십시오 :

from c in dc.Organization
where SqlMethods.Like(c.Hierarchy, "%/12/%")
select *;

Linq-to-SQL *을 사용한다고 가정합니다 (아래 참고 참조). 그렇다면 string.Contains, string.StartsWith 및 string.EndsWith를 사용하여 SQL LIKE 연산자를 사용하는 SQL을 생성하십시오.

from o in dc.Organization
join oh in dc.OrganizationsHierarchy on o.Id equals oh.OrganizationsId
where oh.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

또는

from o in dc.Organization
where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

참고 : * = .net 3.5에서 ADO.Net Entity Framework (EF / L2E)를 사용하는 경우 Linq-to-SQL과 동일한 변환을 수행하지 않습니다. L2S는 적절한 변환을 수행하지만 L2E v1 (3.5)은 t-sql 표현식으로 변환되어 where 절 또는 조인 필터에 더 나은 판별 기가없는 경우 쿼리중인 테이블에서 전체 테이블 스캔을 수행합니다.
업데이트 : 이것은 EF / L2E v4 (.net 4.0)에서 수정되었으므로 L2S와 마찬가지로 SQL LIKE를 생성합니다.


VB.NET을 사용하는 경우 대답은 "*"입니다. where 절은 다음과 같습니다.

Where OH.Hierarchy Like '*/12/*'

참고 : "*"0 개 이상의 문자와 일치합니다. 다음은 Like 연산자에 대한 msdn 기사입니다 .


음 indexOf도 저에게 효과적입니다.

var result = from c in SampleList
where c.LongName.IndexOf(SearchQuery) >= 0
select c;

그러한 코드를 사용하십시오

try
{
    using (DatosDataContext dtc = new DatosDataContext())
    {
        var query = from pe in dtc.Personal_Hgo
                    where SqlMethods.Like(pe.nombre, "%" + txtNombre.Text + "%")
                    select new
                    {
                        pe.numero
                        ,
                        pe.nombre
                    };
        dgvDatos.DataSource = query.ToList();
    }
}
catch (Exception ex)
{
    string mensaje = ex.Message;
}

숫자 문자열과 일치하지 않는 경우 항상 일반적인 경우를 사용하는 것이 좋습니다.

.Where(oh => oh.Hierarchy.ToUpper().Contains(mySearchString.ToUpper()))

.NET 코어는 이제 EF.Functions.Like


이것을 시도하십시오, 이것은 나를 위해 잘 작동합니다

from record in context.Organization where record.Hierarchy.Contains(12) select record;

나는 항상 이것을한다 :

from h in OH
where h.Hierarchy.Contains("/12/")
select h

나는 like 문을 사용하지 않는다는 것을 알고 있지만 백그라운드에서 잘 작동합니다. 이것은 like 문으로 쿼리로 변환됩니다.


System.Data.Linq.SqlClient.SqlMethods.Like("mystring", "%string")

포함 은 Linq에서 사용되며 Like 는 SQL에서 사용되는 것과 같습니다 .

string _search="/12/";

. . .

.Where(s => s.Hierarchy.Contains(_search))

Linq에서 다음과 같이 SQL 스크립트를 작성할 수 있습니다.

 var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});

LINQ에서 "SQL Like"메서드를 찾는 방법을 찾는 것처럼 여기에서 넘어지는 사람들을 위해, 나는 아주 잘 작동하는 것을 가지고 있습니다.

열 데이터 정렬을 변경하기 위해 데이터베이스를 변경할 수없는 경우입니다. LINQ에서 할 수있는 방법을 찾아야합니다.

도우미 메서드 SqlFunctions.PatIndex마녀를 사용하고 실제 SQL LIKE 연산자와 유사하게 작동합니다.

먼저 검색 값에 가능한 모든 분음 부호 (방금 배운 단어)를 열거하여 다음과 같은 결과를 얻습니다.

déjà     => d[éèêëeÉÈÊËE]j[aàâäAÀÂÄ]
montreal => montr[éèêëeÉÈÊËE][aàâäAÀÂÄ]l
montréal => montr[éèêëeÉÈÊËE][aàâäAÀÂÄ]l

그런 다음 LINQ에서 예를 들면 다음과 같습니다.

var city = "montr[éèêëeÉÈÊËE][aàâäAÀÂÄ]l";
var data = (from loc in _context.Locations
                     where SqlFunctions.PatIndex(city, loc.City) > 0
                     select loc.City).ToList();

그래서 내 필요에 따라 도우미 / 확장 방법을 작성했습니다.

   public static class SqlServerHelper
    {

        private static readonly List<KeyValuePair<string, string>> Diacritics = new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>("A", "aàâäAÀÂÄ"),
            new KeyValuePair<string, string>("E", "éèêëeÉÈÊËE"),
            new KeyValuePair<string, string>("U", "uûüùUÛÜÙ"),
            new KeyValuePair<string, string>("C", "cçCÇ"),
            new KeyValuePair<string, string>("I", "iîïIÎÏ"),
            new KeyValuePair<string, string>("O", "ôöÔÖ"),
            new KeyValuePair<string, string>("Y", "YŸÝýyÿ")
        };

        public static string EnumarateDiacritics(this string stringToDiatritics)
        {
            if (string.IsNullOrEmpty(stringToDiatritics.Trim()))
                return stringToDiatritics;

            var diacriticChecked = string.Empty;

            foreach (var c in stringToDiatritics.ToCharArray())
            {
                var diac = Diacritics.FirstOrDefault(o => o.Value.ToCharArray().Contains(c));
                if (string.IsNullOrEmpty(diac.Key))
                    continue;

                //Prevent from doing same letter/Diacritic more than one time
                if (diacriticChecked.Contains(diac.Key))
                    continue;

                diacriticChecked += diac.Key;

                stringToDiatritics = stringToDiatritics.Replace(c.ToString(), "[" + diac.Value + "]");
            }

            stringToDiatritics = "%" + stringToDiatritics + "%";
            return stringToDiatritics;
        }
    }

이 방법을 개선 할 제안이 있으시면 기꺼이 도와 드리겠습니다.

참고 URL : https://stackoverflow.com/questions/835790/how-to-do-sql-like-in-linq



반응형