Does SQL Server automatically trim nvarchar fields upon query?

前端 未结 3 1037
独厮守ぢ
独厮守ぢ 2021-01-18 19:08

I have this query :

select \'[\' + p.Firstname + \']\' from Person p
where p.Firstname = \'Johanne\'

In the table, I have multiple personn

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 19:48

    You could create a new view in Sql and map that view back to an EF object. The view could contain the length of the field(s), in the select using DataLength, you know you want to match against and then you could filter on that in your where clause when you use EF. Alternatively you could create a Sql Stored Proc that does a comparison using LIKE without wild cards (which produces the desired result) and map that back to your code and call it in your Where statement in EF.


    Using View

    Create View MyCustomView
    AS
    SELECT [column1,column2,etc], DATALENGTH(FirstName) AS FirstNameLength
    FROM Person
    GO
    

    Then your EF would be:

    Persons.Where(p => p.FirstNameLength == "Johanne".Length && p.FirstName == "Johanne");
    

    To use a Stored Proc

    CREATE PROCEDURE [dbo].[GetPersons]
    firstName int = null
    AS
    BEGIN
    SET NOCOUNT ON;
    select [your fields here]
    from persons
    where FirstName like @firstName
    END
    

    In C# make sure your mapping is correct and then

    this.Database.SqlQuery("GetPersons","Johanne");
    

    EF6 also supports directly editing the sql in the DbContext before it is executed. You could develop some custom code that replaces the = with like under specific circumstances but maybe easier to try the above first before you do that.

提交回复
热议问题