ADO.NET :: Cast Error When Inserting Record With Linq (to Sql)?
Aug 22, 2010
I'm getting the following error message:
Unable to cast object of type 'System.Data.Linq.DataQuery`1[Username]' to type 'Username'.
I've been searching but can't find a solution. This particular table has 4 columns. The first column is the int indentifier. Column 2 is "username" (varchar50) and is the primary key. Column3 is "userID" (uniqueidentifier) and column 4 is "active" (varchar5)
[Code]....
View 7 Replies
Similar Messages:
Mar 11, 2011
is there any way I can retrieve the identity value (auto generated primary key value), of a column after inserting a new database record using linq to sql? i could i achieve this like this using stored procedure: //***insert some recor*** return @@identity. how do I achieve thesame with linq to sql
View 2 Replies
Apr 3, 2010
I am in a serious trouble right now, i wanted to know that how to write a query in LINQ to SQL to retrieve identity column's current value before inserting any value.
I need this cos i m building a windows app n i need to display this value before inserting a record. I have tried DataContext.ExecuteCommand('DBCC CHECKIDENT (Tablename)') but it returns the number of rows modified.
View 2 Replies
Mar 8, 2011
I have a complicated join between a few tables but I have managed to replicate the error using linqpad and the small tables below. There are references between the COLNAME column and the YAXIS column and also between COLNAME and XAXIS that is not explicitly defined.
The error is "Specified cast is not valid", which originally I wasted time thinking the problem was converting the data returned to my object in VS 2010, but the error also happens in linqpad with no defined object. It seems insane that a bit column would cause this problem. If I change the column type to a VARCHAR it works fine. If I run the generated SQL from linqpad or sql profiler that also returns fine.
[Code]....
View 1 Replies
Jan 14, 2010
I have the logged-in user's Guid stored in a session variable. My understanding is that when the Guid is passed to the session variable it becomes a string. When I use the detailsview control I have to convert the session variable back to a guid and I've been doing it like this and it seems to work fine:
e.values("UserId") = session("LoggedInUserId")
Dim UserId as Guid = New Guid()
When I try to use the Insert() command after the following:
SqlDataSource3.InsertParameters("UserId").DefaultValue = Session("LoggedInUserId")
I get an "InvalidCastException" error with the comment "Conversion from type 'Guid' to type 'String' is not valid." I'm assuming the session variable needs to be converted to a type Guid since that's what I've had to do with the Detailsview control. I've tried a few different ways of converting the session variable back to a Guid so the insert command will work, but no matter which method of conversion I try I get errors such as "value of type system.guid cannot be converted to 'string'. I'm confused because I thought I was supposed to convert it from a string to a Guid. The "UserId" parameter is a non-primary key uniqueidentifier in the database.
View 2 Replies
Nov 7, 2010
public void Add(IDataProvider provider){
var key=KeyValue();
if(key==null){
var newKey=_repo.Add(this,provider);
this.SetKeyValue(newKey);
}else{
_repo.Add(this,provider); //NullReferenceException was unhandled by user code
[Code]....
View 1 Replies
Jan 26, 2011
App Details:
C#, ASP.NET MVC, SQL Server 2008 ( Same version & SP level), Linq-To-SQL ORM
I'm trying to diagnose an exception I'm receiving:
"Specified cast is not valid."
at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager2.TryCreateKeyFromValues(Object[] values, V& v)
at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache2.Find(Object[] keyValues)
at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues)
at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues)
at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()
at Repository.Save()
at etc....
The problem is that this is occurring only on our servers, not on our local development boxes. I've tracked it down to a single property we're modifying:
event.SalesForceId = "701Q0000000AOTIIA4";
If I comment out that line, everything works fine.
I've tried:
1 ) waxing all of the code on the server and redeploying. Same issue.
2 ) Pulling down a copy of the server DB and trying it locally. Works fine.
3 ) Trying another IIS environment we have setup on the same box. Same issue.
4 ) Physically comparing ( using AdeptSQL ) both local and remote schemas. No differences.
5 ) Verifying the datatypes of both columns ( local and remote ) are the same. Also, this column is a FK to another table. I verified that both are of the same data type, down to the collation.
The server is Windows Server 2008 and the local box is Windows 7 x64. Both have all important updates setup.
The only thing I can think of is perhaps since the database and web server are on different boxes that could be an issue? Otherwise, I'm completely stumped.
View 2 Replies
Dec 20, 2010
I am creating an album using the following stored procedure, which returns the primary key for the newly created record:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[fpa_sp_albums_update_insert]
@album_id int,
@album_name nvarchar (50),
@album_descr nvarchar(250),
@album_img_cover_id_FK int,
@album_creation_date date
AS
If @album_id > 0
UPDATE [fpa_albums]
SET
album_name=@album_name,
album_descr= @album_descr,
album_img_cover_id_FK = @album_img_cover_id_FK,
album_creation_date = @album_creation_date
Where ((album_id = @album_id))
Else
INSERT INTO [fpa_albums] (
album_name,
album_descr,
album_img_cover_id_FK,
album_creation_date)
VALUES (
@album_name,
@album_descr,
@album_img_cover_id_FK,
@album_creation_date)
Return SCOPE_IDENTITY();
I execute the above stored procedure using the SQLHELPER. The VB.NET code for the page is as follows:
[Code]....
However, the createdAlbumID always shows -1 instead of the id for the newly created album.
View 1 Replies
Apr 1, 2011
table1 row = _db.table1.FirstOrDefault(r => r.ReferenceID == refNumber);
Is there anyway to cast row to IEnumerable?
((IEnumerable<table1>)row) - does not work
View 1 Replies
Oct 28, 2010
I am having problem, these are the errors:
[Code]....
These are the codes:
[Code]....
View 2 Replies
Jun 29, 2010
just needing a 2nd set of eyes looking at this to make sure the error isn't something else other than my LINQ code here. Here's the function class itself:
[Code]....
For some reason it's flagging the 2nd line in the GetJacketByPolicyID function saying the specified cast is not valid. So I'm guessing it's something I'm doing wrong. I'm sure the tblPolicy/tblPolicies class works right since I can create a new instance of a tblPolicy and set a few variables by hand and return it, so that's not it. I've also checked the datarow I'm fetching and there's no null values in the record, so that shouldn't be it either.
View 2 Replies
Mar 28, 2011
I have a database table called Animals which I drag on to my Linq to SQL DBML file.
This creates me a class called Animal.
I then create a class to extend it, like so:
public partial class Animal{
//my extra code here
}
But what I also want to do is have a class like this:
public class Zebra : Animal{
//even more extra code here
}
The trouble is I get an InvalidCastException from my repository, when I do this:
Animal a = dataContext.Animals.Where(c=>c.id.Equals(id)).SingleOrDefault();
return (Zebra)a;
I've stripped back my classes to the point where they're completely empty in an attempt to work why it doesn't work. To no avail.
This casting process did used to work in the non-LINQ-2-SQL project that I'm switching to MVC/LINQ.
View 1 Replies
Mar 31, 2010
I wanted to delete the record from data but I receive this error "Unable to cast object of type 'System.Data.Linq.DataQuery`1[training_eval.Course]' to type 'training_eval.Course'.
Dim eval_sure = From ev In db.Evaluates Where ev.course_id = indexcourse Select ev.course_id
Dim del_course = From c In db.Courses Where c.Course_id = indexcourse
db.Courses.DeleteOnSubmit(del_course)
db.SubmitChanges()
View 4 Replies
Oct 10, 2010
[Code]....
[Code]....
[Code]....
[Code]....
[Code]....
View 2 Replies
Aug 14, 2010
Students can subscribe for any project via a webform. Table 'project ' contains all the proposed project and table 'student' contain the name of the student and the project-id.Now, suppose there is a limit of 4 students for project 'A' and there are already 3 subscribed students for that project. One more student can choose that project. The code-behind checks whether the limit is not reached (by counting the amount students for that project in table 'student') before inserting that student in the table 'student'.
My problem is that when two students fills the webform for the same project and click on the 'save-button' exactly at the same time, the code has no time to check the limit and both students are inserted into table 'student'. Is there a way to lock the table or something in order to preventing this?
[Code]....
View 5 Replies
Aug 4, 2010
I am using ASP.NET 2.0, C#, SQL Server 2005. I have a gridview which has 10 records. I want to only insert few records(for example: 3 records) to the database. How to insert only part of the whole data to the database.
View 3 Replies
Dec 26, 2010
i got the following error when i tried to inser a recrord from my MVC web application , although the insert will work fine when i tried to inser the record manually from the databse explorer, and i checked all the FK relationship they sound valid:-
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Articles_Users". The conflict occurred in database "84A669DA0E532BEFAFBE7BE38367071F_IONALNETWORKWEBAPPLICATIONPROFESSIONALNETWORKWEBAPPLICATIONAPP_DATAPROFESSIONALNETWORKDB.MDF", table
"dbo.Users", column 'User_ID'.The statement has been terminated.
View 12 Replies
Mar 16, 2010
I'm a new user of ASP.NET MVC and I'm trying to replicate the ListView control from WebForms in an AJAX-y manner. Take the following as an example:
[Code]....
The "ItemTemplate", "EditItemTemplate", and "InsertItemTemplate" replacements are implemented as Partial Views, so the view for this page looks something like this:
[Code]....
The edit/update flow is very simple. The user clicks the "edit" button, an AJAX request is made to get the "EditItemTemplate", and the contents of that row are replaced with the "EditItemTemplate". When the user clicks "Update" in the edit row, the form is submitted via AJAX and the resulting content replaces the "EditItemTemplate".
The part I'm not sure how to deal with is the InsertItemTemplate. When the user submits the insert form, I need two partial views to be returned: one to replace the InsertItemTemplate (clear the form or show any validation errors), and one to insert into the table as a new record (ItemTemplate). I'm not sure what to do about this...the only options I've come up with are:
Make 2 Ajax requests -- one to insert the item and get the ItemTemplate for the new item and another to get a clean InsertItemTemplate Make 1 Ajax request for JSON -- render the ItemTemplate and InsertItemTemplates into strings and then put them into a JSON object that can be analyzed client-side (ex: { itemtemplate: "<tr>...</tr>", insertitemtemplate: "<tr>...</tr>" }) Make 1 Ajax request for the ItemTemplate and then manually clear the InsertItemTemplate form client-side (removing any form entries and validation elements)
None of these options really seem that great to me...especially #1 (because of a second AJAX request) and #3 (because it keeps my solution from being easily reused on other "ListView replacements" due to the need to manually clear the form). #2 is somewhat acceptable but still kind of hacky because rendering partial views to strings and then sending them in JSON isn't easy to do and ends up being a bit of a hack.
View 5 Replies
Mar 22, 2010
i am inserting a record into oracle database using vb.net,there is a password field by using md5 i am generating it and taking tht value as string(ex: "16D78A6B10D631C8C86397C35A3CCD57") now my requirement is i should insert it into database(oracle) & in database that field is "RAW" how to do this?and the error msg is
Type of value has a mismatch with column typeCouldn't store in Col_Pass Column. Expected type is Byte[].
View 1 Replies
Jun 9, 2010
Im trying to get the ID out of the record that i'm inserting using scope_identity. I've add the following line of code to the Insert statements in the sqldatasource - SET @insID = Scope_Identity() I've add the following line to the Insert parameter list
asp:Parameter
Name="insID"
Type="Int32"
Direction="Output"
I now want to insert a number records into the database using the following:
Dim insID As Object = e.Command.Parameters("@insID").Value ' gets out latest ID
Dim ordernumber As String = "CX" & insID.ToString & DateTime.Now.DayOfYear.ToString
sqlOrders.InsertParameters("orderNumber").DefaultValue = ordernumber
sqlOrders.InsertParameters("orderDate").DefaultValue = DateTime.Now
sqlOrders.InsertParameters("customerID").DefaultValue = userID
sqlOrders.InsertParameters("productID").DefaultValue = productID
sqlOrders.InsertParameters("totalPrice").DefaultValue = "0.00"
sqlOrders.InsertParameters("status").DefaultValue = "Paid"
I currently have this code in the SQLDataSource_Inserting sub but the first line only works once the record is inserted. How can i get the ID out as im inserting the parameters?
View 3 Replies
Jul 16, 2010
I am wanting to insert a record into a table in SQL then retrieve its key at the same time, the key is a int that is automatically generated, I read something about the '@@Identity' function, is this what I need? How could I then bind this to a label in the ASP.net page?
View 12 Replies
Aug 25, 2010
Is there any way to make sure an Insert Command happens before the Page_Load Events? I'm having a problem with inserting, then reading the DataSet directly after. It seems it processes too quickly, or prior to the record being inserted. It has an impact on the DataSet that is to be displayed on screen. Summary:
Page_Loads > Finds Saved Data > If None exists (string contains 2 types of matches) > Displays the 1 of 2 types randomly.
Buttons 1 & 2 Insert their respective options > Page Posts Back > Page_Loads > Read Saved Data > If my Max amount of the 1 of 2 types of Data are reached, the remaining type is shown > Displayed on page The problem I am having is that my DisplayDataSet is not getting the correct values. It seems it's always 1 record behind on the count, because the count happens so fast, it's not getting the record that was just inserted. How can I write this, or make sure the "Find Saved Data' Routine happens after the Insert has been preformed?
[Code....]
View 2 Replies
Dec 15, 2010
I need a way to opening a new window after inserting a new record. I'm using object data source for CRUD and my code looks something like this:
Private Sub odsFileNote_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs) Handles odsFileNote.Inserted
If e.Exception Is Nothing Then
Page.ClientScript.RegisterStartupScript(GetType(Page), "newWindow", String.Format("<script>window.open('{0}');</script>", "www.google.com")).........
View 5 Replies
Oct 30, 2010
I am creating roombooking website in asp.net.
and i am facing problem while inserting the record.
eg:
if the room is already booked from 1st march 2010 to 10th march 2010.and if anybody is booking the same room from 4th march to 9th march it should show error message stating that
this room is already booked from 1st march to 10th march.
View 1 Replies
Aug 18, 2010
I've already checked the row returned by my sproc and all the fields match my OcItemConstraintDetails class.
Not sure why I am getting the error below :(Error: Specified cast is not valid.
[Code]....
My code:
[Code]....
View 4 Replies