1

I've been working with Linq to SQL for some time now, and I never had a problem ... until now. I have a method that send a query to the database, but different from the other times I did it, I cannot cast the result (be it to List or to Array). The method look as follows:

public List<vwContainer> GetConteinerPorto(int id)
{
    return (from cont in db.vwContainers
            where cont.idHarbor == id
            orderby cont.Year
            select cont).ToList();
}

I tried some variations of it, but it always result with a "Specified cast is not valid." exception being thrown. Can you guys give me some light?

Stacktrace:

[InvalidCastException: Specified cast is not valid.]
   System.Data.SqlClient.SqlBuffer.get_Int32() +6271252
   Read_vwCargas_movimentadas_conteiner(ObjectMaterializer`1 ) +636
   System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +42
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +472
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
   WebPortosSEP.Web.Models.PortoRepository.GetConteinerPorto(Int32 id) +867
   WebPortosSEP.Web.Controllers.PortoController.Cargas(Int32 id) +255
   lambda_method(Closure , ControllerBase , Object[] ) +112
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709
   System.Web.Mvc.Controller.ExecuteCore() +162
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371
2

6 Answers 6

4

This might be because of the mismatch between the types of columns in the database and the .Net types.

When the values of fields like cont.idHarbor and cont.Year are read from the database and converted to .Net types the resulting types may not match those of the properties in your class.

Check if idHarbor is bigInt in database and you are comparing it with an int. Also check the Year field types. You can take a clue from the stacktrace. Is the exception thrown by SqlDataReader.GetInt64 or any such similar method?

Sign up to request clarification or add additional context in comments.

9 Comments

I used VS itself to create the ORM, and it seems to work fine for all the other tables. Also, I checked the generated class and all the types are ok.
could you please provide the stack trace of the exception?
The exception is thrown by SqlBuffer.get_Int32(). So it must be the runtime conversion which is resulting in an invalid cast. I suspect the comparison in your where clause. Could you please omit the order by and select clause from your query and test.
Omitted orderby (select is not possible to omit) and failed as well. Also, changed the where clause to use Year instead of ID and got the same error. Could it possibly be because of the generated class uses nullable integers instead of just int?
Is the field nullable in the database? Are there nulls in the data?
|
2

It would seem that cont is not actually a vwContainer.

3 Comments

If this would be the case, wouldn't the error appear at compile time already?
Give it a try and explicitly cast "cont" to vwContainer, either by doing "from vwContainer cont in ..." or by ".. select (vwContainer)cont".
Tried that VVS solution, but it didn't work. Also, when I mouseover 'cont' the intelisense says it is from the right type.
0

Your method does not contain any cast. Are your sure the Exception is throw from within the method and not from its call site?

1 Comment

I'm quite sure. I rearranged it so many times, and also using other tables (which worked).
0

Try this:

 public List<vwContainer> GetConteinerPorto(int id) 
 { 
    return (from cont in db.vwContainers 
           where cont.idHarbor == id 
           orderby cont.Year 
           select cont).ToList<vwContainer>(); 
 } 

1 Comment

Tried and received the same result.
0

It's possible you changed the database schema (e.g. an into to a string) and didn't update the DBML (you would only see this error at runtime when you first access the table that has the error)

4 Comments

Updated the dbml just to be sure and it didn't make any changes.
System.Data.SqlClient.SqlBuffer.get_Int32() +6271252 Read_vwCargas_movimentadas_conteiner(ObjectMaterializer`1 ) +636 This indicates that when it is trying to read one of the values from the vwCatgas_movimentadas_conteiner object it is expecting an int (the DBML has told it so) but the database gave it something that isn't one.
Just checked the DB, and it is an int.
Try switching on the logging with DataContext.Log to see what TSQL is being sent.
0

If it's a runtime exception and not a compile tome error, then the problem is almost surely that your dbml file is out of sync with your database on some level. I have also seem similar problems when you have more than one dbml file in the same namespace.

Try deleting the table in question out of the dbml file and recreate it.

UPDATE:

Based on your stacktrace, I find it highly suspicious that your exception occurs within a lambda method, but the code you have sown does not include any lambdas. That's not to say there might not be an internal lambda going on, but I don't think so.

Also, note that your stack trace includes this:

Read_vwCargas_movimentadas_conteiner

That's different from the code you posted.

Update 2:

The exception is occuring in an Int32 conversion, which suggests that one of your data columns is not correctly defined. Did you change the type from nullable to non-nullable?

6 Comments

I'm from Brazil, so I translated the name to make you guys more comfortable with the example. Unfortunately I have to program in portuguese, which sucks.
Well, it helps to debug if you give the real code and not a translation, because all too often real bugs are subtle and can get lost in a translation.
Updated the dbml just to be sure and it didn't make any changes. Also, I ToString()'ed the result and got the SQL, checked it against the DB and it worked ok.
I'm not sure i understand, are you saying that updating the dbml fixed your problem? I don't know what you mean by "and it worked ok" is supposed to mean here.
This worked ok means that the query generated by Linq (which I could retrieve by using ToString()) worked ok when checking it in SQL Server, it is, should be working inside my project, but it doesn't.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.