问题
I've hit an error when I've been working on a table that uses a text field.
If I was getting the length of a varchar column I could do
var result = (from t in context.tablename select t.fullname.Length)
However, if I run the same query on a text field:
var result = (from t in context.tablename select t.biography.Length)
I get the error :
Argument data type text is invalid for argument 1 of len function.
Having done a bit of reading up on the subject I understand why SQL Server raises this error but I'm not sure of the best way around it. I know I could return the result and then get the length of the resulting string but surely there is an easier way of doing this?
回答1:
I think your best option is to update the column data type to VARCHAR(MAX) if it is TEXT or NVARCHAR(MAX) if it is NTEXT. There are plenty of resources on how to do this, but generally you make a new column of [N]VARCHAR(MAX) and then you update all your data across into the new column, then drop the old column and finally rename the new column to the old name.
If you can't change the table schema, then you will need to create a view and do the type casting in the select of that view.. but then you might as well have just changed the column data type as mentioned above (unless you're not the db owner and you create the view in a different database). But be mindful that EF doesn't always play as nice with views as it does with tables.
来源:https://stackoverflow.com/questions/10316015/entity-framework-getting-the-length-of-data-in-a-text-column