问题
In SQL Server, uniqueidentifier
columns can be used like strings with the LIKE comparison:
SELECT * FROM dbo.Table WHERE GuidColumn LIKE '4c38e01e%'
How can I use this feature in Entity Framework?
I want something like this
context.Table.Where(x => x.StringColumn.Contains("some string"))
but for a Guid column instead for string columns:
context.Table.Where(x => x.GuidColumn ???? "4c38e01e")
回答1:
As far as I know there is no way to convert Guid to string on the fly in EntityFramework. I'm aware of some workaraounds but they are not elegant to me though they may be helpful in your case:
- Create a view in SQL server where you convert your Guid column to string. Then create a new entity and map it to the view. Now you have your guid column in a string represantation and can apply 'like' operator. The main drawback is query performance.
- Create a PERSISTENT calculated column of string type. Use convert expression to convert your Guid to string. Query performance would be the same as for an ordinary string column, but it will take a bit longer to insert records into your table.
- If this is not the only filter applied to your data source then maybe you can apply your GUID LIKE operation when the data is already in memory.
Hope it helps.
回答2:
I worked around this by creating a stored procedure in the database that handled the 'like' clause in the database, and mapping the procedure results to my entity from the edmx. So my stored proc is:
CREATE PROCEDURE [dbo].[spGetDevicesWhereGuidContains]
@partialGuidString as varchar (5)
AS
BEGIN
SET NOCOUNT ON;
SELECT * from devices where [Guid] like '%' + @partialGuidString + '%'
END
Then, mapping the proc to the entity from the model browser: http://entityframeworktutorial.net/data-read-using-stored-procedure.aspx#.UT0F96GG1e4
Then it's obvious from there;
List<Device> devices = context.spGetDevicesWhereGuidContains("8").ToList();
Not ideal, but does the job.
来源:https://stackoverflow.com/questions/14118654/how-to-use-sqls-like-on-a-guid-in-entity-framework