.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Post New Web Links

Cast error when inserting record with Linq (to Sql)

Posted By:      Posted Date: August 23, 2010    Points: 0   Category :ASP.Net


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) .

            Dim dc As New DataClassesDataContext
            Dim c3 As New Username With {.userID = userGuid, _
                                    .username = userCustomName, _
                                    .active = "False"}


        Catch ex As Exception
            Throw ex
        End Try


View Complete Post

More Related Resource Links

Inserting personal error message in ValidationSummary



I am creating a web form that requires a lot of validation. I use many of the validation control in asp.net already like RequiredFieldValidator and CompareValidator. 

My Problem: after my custom validation for the value entered return an error message, and I pressed enter key when the field is empty, my custom error message is overlapped by my ValidationSummary. 

Setting my custom error to visible = false on button click also does not seem to work as it requires for me to enter the value first.

This made me think, is there a way to insert my custom validation inside the ValidationSummary as an error message like for other validation control?

Thanks in advance

LINQ to SQL - Validating if item is in Database, but if item is not items not inserting into databas



I am new to this, so bear with me.  I am writing an application in C# that uses LINQ to validate a datacontext off a textbox to see if the record exists already.  If the record does exist I inserted an if statement to advise the user that the record exists, if the record does not exist I would like to allow the record to be added to the database.  If I take out my else statement everything works fine as far as inserting goes, but I do not want to allow inserts in this scenario.  I have tried moving the if and else statement to different parts of the code but can't quite figure this one out.  Any help would be apprecaited, attached is the code.  This code is set to a button press.  As a matter of fact, if you see any other errors along the way please feel free to point them out. 



    protected void enterBTN_Click(object sender, EventArgs e)
        //make new data context

        SHCDataContext insNewAll = new SHCDataContext();
        //LINQ to check if customer exists in database
        var checkExisting = from c in insNewAll.Customers
                            where c.custLastName.Contains(custLastNameTB.Text.ToString())
                            select c.custLastName;
        //make list to store values

Need Help in LINQ query for group By with chunks of record


I am assigning and unique id [strShipperIdSequence] on my List on bases of some properties which are grouped together uniquely.
Now what i needed is that my group should be further break down to some maximum amount of chunks.[Let say 10]
that mean's even i am having Same value in 12 records i should get 2 groups[I of 10 items and other of 2 items]

var uniqueGroups = objMdbContentInfoList.GroupBy(p => new
}).Select(g => g.First()).ToList();
foreach (var objUnique in uniqueGroups)
string strShipperIdSequence = APIGlobalMethods.GetShipperRequestID();
foreach (MdbContentInfo obj in objMdbContentInfoList.FindAll(h => (h.CON_ENTRY_POINT == objUnique.CON_ENTRY_POINT &&
h.APPTType == objUnique.APPTType &&

linq and max, if return null return error


hi there
i have this query :

var result2 = (from TH in DB.Threshold
                          where TH.ProductSKUID == int.Parse(HID_ProductSKUID.Value)
                          select TH.ThresholdID).Max();

the problem is that if this query does not find any items, return null, so thow exception
how can i do to return 0??

Linq getting data from field on record



   I would assume this is possiable but I cannot seem to find it anywhere. I just one the contents of a single field, I don't see why I have to return the how

record to get get that information, here is my current code, how can I make this better without returning the entire record, for just getting contents of one field.

var patternrecord = storedb.Patterns_Table.Single(a => a.Pattern_GUID == id);
PMEDIA.Pattern_Key = patternrecord.Pattern_Key;

>>>Check duplicate while inserting record from Texbox.

Hi, On inserting record, I want to check that for example if a user enters a telephone number for any record is already in the database then it should validate that the number already exists in table and you cannot enter a duplicate value. Then if user will provide some other telephone number then he allows to insert record. For insertion of record I used ObjectdataSource. User will enter telephone number in a simple textbox. I may want to inform that I am working in asp.net2.0 and also not allowed to use any third party control or ajaxtoolkit. Any idea would be appreciated.

LINQ to SQL compiler error CS1519: Invalid token 'void' in class, struct, or interface member decl

I get the following compiler errors when creating my first LINQ to SQL class (I just dragged a table "ProfileExtended" onto the designer and hit build):DataClasses.designer.cs(31,11): error CS1519: Invalid token 'void' in class, struct, or interface member declaration these are the offending lines of autogenerated code:#region Extensibility Method Definitions  partial void OnCreated();  partial void InsertProfileExtended(ProfileExtended instance);  partial void UpdateProfileExtended(ProfileExtended instance);  partial void DeleteProfileExtended(ProfileExtended instance);  #endregion

Missing a cast in Linq Expression

 Hi, My code is: var results = from XPathNavigator res in iterator  where res.Select(xpath).Current.Value.Contains(param) select res; where iterator is XPathNodeIterator. I get the next error(on where ): Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Xml.XPath.XPathNavigator>' to 'System.Linq.IOrderedEnumerable<System.Xml.XPath.XPathNavigator>'. An explicit conversion exists (are you missing a cast?) Where am I  missing a cast? Thanks, katzraya        

Page_Load Order -- Inserting a record

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?  Imports System.Data Imports System.Data.SqlClient Partial Public Class Assessment1 Inherits System.Web.UI.Page Protected Sub btnINS1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnINS1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim s

LINQ Error

Dear all, I have below code. But It throw exception that System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: Cannot order by type System.Object.    at System.Data.Linq.SqlClient.QueryConverter.VisitOrderBy(Expression sequence, LambdaExpression expression, SqlOrderType orderType)    at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)    at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc)    at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)    at System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)    at System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)    at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)    at System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()    at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)    at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)   public List<KeyValue> GetStockTypes()        { &nbs

Questions on inserting to Linq to Sql

I have a situation that I can't figure out.  Say I have tableMain, and tableSub.  Say I have an association in the dbml between tableMain and tableSub such that tableMain is the parent class and tableSub is the child class.   I can't insert any records programmatically into tableSub.  I get a "Specified cast is not valid." error.  If I remove the association and run the exact same code, the record is inserted without a problem.This has been an issue for me for some time.  I've resorted to haveing a second dbml to use when inserting records into tables with an association with my main table, but I don't like having tables in more than one dbml unless it's really necessary.  It's too easy to forget to update a dbml when changing a table structure.Does anyone know why this is happening?

How can you use Linq to SQL to get the primary key of a record you've just inserted?

Hi,I'm inserting data into a database with Linq to SQL and would like to access the primary key of that record WITHOUT doing a query for the values I've already captured.Here is my insert startment: Dim page As New pageData With {.pageTitle = txtPageTitle.Text, .pageDescription = txtPageDescription.Text, .pageContent = HttpUtility.HtmlEncode(txtPageContent.Text) }There is a value in the table that is an auto increment integer.Rather than doing a query for the pagetitle, description and content I'd like to just access the primary key that I would have just generated by performing the insert.Is this possible or would I have to perform the query as I've just mentioned to retrieve it?

Flat file upload: Error when inserting into datetime field.

Hi All I am having an issue with uploading a txt file into an SQL table and one of the fields needs to go into a datetime column. The issue is with column3 I have been into the advanced editor of the flat file source and set the output column to decimal and it fails. The error I am getting is below: Error: 0xC02020A1 at Materials Transfer, Flat File Source [1]: Data conversion failed. The data conversion for column "Column 3" returned status value 2 and status text "The value could not be converted because of a potential loss of data.". Error: 0xC0209029 at Materials Transfer, Flat File Source [1]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "output column "Column 3" (48)" failed because error code 0xC0209084 occurred, and the error row disposition on "output column "Column 3" (48)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure. Error: 0xC0202092 at Materials Transfer, Flat File Source [1]: An error occurred while processing file "D:\Development\r3_downloads\mat.txt" on data row 1. Any help would be great.   Thanks BigGopher

linq - no record

If this search does not record how I write: "No record" and if the records: "Record"         var creditcard = from p and db.tbl_Payments                          WHERE userid == p.UserId                          select new                          (                                    UserId = p.UserId,                          );thanks

DetailsView error "must be in edit mode to update a record" when I have set edit mode in code behind

Hi,I have a DetailsView within an UpdatePanel.  I programmatically put the DetailsView into edit mode, change the fields then call the UpdateItem method which causes the "must be in edit mode to update a record" exception.  Am I missing something blindingly obvious? <asp:UpdatePanel ID="upSpecificShout" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true" > <ContentTemplate> <asp:DetailsView ID="dvSingleShout" DataSourceID="sdsSingleShout" runat="server" AutoGenerateRows="false" OnDataBound="SetDVIcons" HeaderStyle-CssClass="noDisplay" DefaultMode="ReadOnly" AutoGenerateEditButton="true" OnItemCommand="dvItemCommand"> <fields> <asp:TemplateField ShowHeader="false"> <ItemTemplate> <asp:Panel ID="dlSpecificDetailsViewPanel" runat="server" CssClass="i_am_a_shout"> <h2><asp:LinkButton ID="lblShoutTitle" runat="server" Text='<%# Bind("Shout_Title") %>' On

error in inserting data into the datasource


hello all i have a gridview and textbox i want to insert the data that typed in the textbox  into the gridview i can do this but in other culomn i just can insert number 
and when i type some world the error say:Invalid column name'every thing ' 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="soal.aspx.vb" Inherits="soal" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
            width: 100%;
<body bgcolor="#fe9cef">
    <form id="form1" runat="server">
    <table class="style1">
                <asp:GridView ID="GridView1" runat="server" AllowSorting="True" 

Compilation error after inserting script


I have a one page ASP.Net site; there is no separate code-behind file.  It pulls its data from a SQL ODBC connection; All was well, until I tried to include script to change the color of the row, based on a condition.  Normally, the backcolor is black; and the forecolor is white; the forecolor should change to blueviolet when the field "flex_in" is not null.  Here is the code:


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend