Linq-To-SQL Reports That The Query Operator 'Last' Is Not Supported
May 30, 2008
All --
Please help.
Why is it that Linq-To-SQL reports that the query operator 'Last' is not supported?
The target database is SQL Server 2005.
The data provider is SqlClient.
This is the error...
System.NotSupportedException: The query operator 'Last' is not supported. 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.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.Last[TSource](IQueryable`1 source)
This is the code.
public static Guid GetPkIdOfLast()
{
Guid myPkIdOfLast = Guid.Empty;
DataClassesDataContext myContext = new DataClassesDataContext();
myPkIdOfLast = (from p in myContext.CountryCodes
orderby p.Name ascending
select p.PkId).Last();
return myPkIdOfLast;
}
Do you have any ideas?
Please advise.
Thank you.
-- Mark Kamoski
View 6 Replies
ADVERTISEMENT
Jul 25, 2007
Hi all, when i create a reports deploy on the Report server, i usually choose a filter prompted on Run. The lsit containt for example the list of my customers, but the list in empty like i want (like that, user can put a list from excel by copy-paste). But ... , if the want all the customers, what is the " * " operator to select all my records ?
Thanks for help
Erwan, France
View 1 Replies
View Related
Feb 29, 2008
I need some help. I have a function that used to use ADO.NET to return a dataview. Now I'm using linq, and I don't know how to make this work anymore.my original function looked like this: public DataView getIssue() { //do some ADO, return the dataview return ds.Tables["Articles"].DefaultView; } With this I could write Gridview1.dataSource = getIssue();I want to do the same thing with Linq, but I'm running into some trouble:Here's my function now:public DataView getIssue() { var query = from a in db.Articles join i in db.Issues on a.IssueID equals i.IssueID select a; DataView dv = new DataView(); dv = query.asdatatable(); return query; }OK, first off I can't use asdatatable since I am using a join, so I can't make the results of my query a dataview. I can't return the results of my query in this function, something that seemed simple to do in Linq now seems like something that may only be possible in ADO.Thanks for your time
View 5 Replies
View Related
Aug 13, 2007
Hi all:
for example: testDataContext db=new testDataContext();var res=db.tables.single(p=>p.columnName=="hi");
if there is a record in the database, it works well, but if there isn't , it will throw an exception, then , How could I know the record exists or not ? I don't think exception is a resonable way. and in my opinion, there should be--------even must be ------a resonable way , to evaluate the query result to a bool variable, then program could judge the bool variable like :
if(bExist) show("yes, I find it");else show("sorry, the record doesn't exist in the database");
I can't imagine I got the bool variable via exception...
thanks to all..
View 1 Replies
View Related
Mar 31, 2008
I have an example : A Simple Database Query using LINQ to SQL
Before creating the project, I using SQLmetal to generate the Nosthwind Entity Classes "Northwind.cs"
c:sqlmetal /namespace:nwind /code:Northwind.cs /pluralize /functions /sprocs /views "C:CongChinhNorthwindNorthwind.mdf"
and then, I add the Northwind.cs in my project.
CODE 1 using System;
2
3 using System.Linq;
4
5 using System.Text;
6
7 using nwind;
8
9
10
11 namespace Ex
12
13 {
14
15 class Program
16
17 {
18
19 static void Main(string[] args)
20
21 {
22
23 Northwind db = new Northwind(@"Data Source=.SQLEXPRESS;Initial Catalog=Northwind");
24
25 var cust =
26
27 from c in db.Customers
28
29 where c.City == "Rio de Janeiro"
30
31 select c;
32
33 foreach (var kh in cust) //---> SQLException was unhandled
34
35 Console.WriteLine("{0}", kh.CompanyName);
36
37 Console.ReadLine();
38
39 }
40
41 }
42
43 }
But when I run the program. It throws a SQLExecption : Login failed for user ''. The user is not associated with a trusted SQL Server connection.I'm using SQLExpress and server name : CONGCHINHSQLEXPRESS and Windows Authentication
I don't know how to solve this problem. Somebody help me,please !
View 1 Replies
View Related
Aug 4, 2015
I'm trying to translate this portion of VFP code into LINQ query:
select COUNT(ID) as conflicts
from dbo.max4sale where <<thisform.cWhere>>
AND Start_Time >= <<VFP2SQL(m.ltBegin + m.lnStartTime)>>
and Start_time <= <<VFP2SQL(m.ltEnd)>>
AND CONVERT(varchar(5),Start_Time,108) <= <<VFP2SQL(m.lcEndTime)>>
AND CONVERT(varchar(5),End_Time,108) >= <<VFP2SQL(m.lcStartTime)>>
<<m.lcDays>>
Here is my non-working attempt:
var startTime = new DateTime(1900, 1, 1, beginDateTime.Hour, beginDateTime.Minute, 0);
var endTime = new DateTime(1900, 1, 1, endDateTime.Hour, endDateTime.Minute, 0);
var daysOfWeek = dailyLimits.Where(dl => dl.Selected == true).Select(ds => ds.WeekDay).ToList();
if (daysOfWeek.Count() < 7) // not all days of the week selected
[Code] .......
First of all, I see a bug in my logic now as the first part of the query I need to do all the time and only the second part if the count < 7. But that's not my problem - I can not figure out how to make times comparison only using LINQ. Ideally I think I'd like to have cast(start_time as time) >= @p1 as a result to be executed by LINQ.
BTW, I am only getting the error in run-time that Parse can not be interpreted. So, I need to figure out another way of making LINQ recognize my intent of checking time portion of the date only.
View 9 Replies
View Related
Jan 21, 2008
I have the following query:
select * from
(
select FLATTENED NODE_CAPTION,
(SELECT
[PROBABILITY],
[ATTRIBUTE_NAME]
FROM
NODE_DISTRIBUTION
WHERE
(
ATTRIBUTE_NAME ='Product A'
and
ATTRIBUTE_VALUE='Existing')
and [PROBABILITY] > 0.5
) as probabilidad
FROM [Cluster XYZ].CONTENT) as T
where T.[probabilidad.PROBABILITY] > 0
and T.[probabilidad.PROBABILITY] <> 1
order by T.[probabilidad.PROBABILITY] DESC
I need to add more products (more Attribute_Name) to the query. I tried to use an 'IN' operator, but I received an error.
I need something like:
ATTRIBUTE_NAME in ('Product A', 'Product B','Product C')
Thanks for your help!
View 1 Replies
View Related
Jul 15, 2007
I'm using VS 2005, and I built a website with a TableAdapter method using the wizard.I hand wrote a line of code: 1 WITH srtAS
2 (
3 SELECT *,
4 ROW_NUMBER() OVER (ORDER BY date DESC) AS 'RowNumber'
5 FROM table1
6 )
7 SELECT *
8 FROM srt
9 WHERE RowNumber BETWEEN @start AND @end; I didn't find any syntax errors, but the Wizard keeps alerting "the over sql construct or statement is not supported." From my research, I found that it's caused by the Wizard that doesnt support some syntax. Afterall, the problem is:1. I have two parameters @start AND @end. normally if there is no "syntax error", then it will show in the TableAdapter: GetData(@Start,@end). But now since there is this "Syntax error", I won't load these two parameters.2. I saw some solutions to this "syntax error" problem, and they suggested to write query manually, don't use wizard. But I don't know how. thanks in advance-noPC-
View 4 Replies
View Related
May 22, 2008
Hi
Just wondering if anyone has the following problem when performing a query similar to the one below:
SELECT PMKeySID
FROM STG_OSIRIS_Person
WHERE (CAST(PMKeySID AS varchar(20)) NOT IN
(SELECT PMkeyS_Number
FROM STG_Person_Dimension
WHERE (Data_Source_Key = 2)))
This query does not bring back any data in SQL Server 2005 Management Studio, however in SQL Server 2000 Enterprise manager it brings back data no problems what so ever. I have tried using this in a OLE DB source object in SSIS as well but to no avail. From what I can determine, this happens on an intermittent basis, it was working! is it a possible bug with SQL Server 2005?
Regards
Wizardlee
View 9 Replies
View Related
Sep 28, 2015
I have 2 tables Table1Â contains Week , Week end date columns
Week  Week end date
W01Â Â Â Â 2015-01-02
W02Â Â Â Â 2015-01-09
W03Â Â Â Â 2015-01-16
Table2 contains ID date column and date columns contains all the dates
IDÂ Â Â Â date column
01Â Â Â Â Â 2015-01-02
02Â Â Â Â Â 2015-01-03
03Â Â Â Â Â Â Â 2015-01-04
04Â Â Â Â Â Â Â 2015-01-05
05 Â Â Â Â Â 2015-01-09
I want to select all the rows from Table2 and Week column from Table1. when I made the join condition I am getting only week end date records from Table2 . how can I select other date records?
View 6 Replies
View Related
Aug 26, 2015
I have a the following query which takes long time
DECLARE @ACCOUNTS TABLE(ACCOUNT_ID INT)
INSERT INTO @ACCOUNTS
SELECT ACCOUNT_ID FROM ACCOUNT
WHERE A_DESCR in ('AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG')
I used the following key words: sql server query tuning in operatorÂ
View 2 Replies
View Related
Jan 22, 2008
Hi, Please could someone assist - the above error occurs. This is my code: Protected Sub btnReport_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Response.Redirect("CrystalreportTEST_Print.aspx?C_id=" & ddlCompany.SelectedValue) Dim myConnection As New OleDbConnection(connString) Dim Str As String = "SELECT clientid,company FROM Client WHERE company =" & ddlCompany.SelectedItem.Text Dim cmd As New OleDbCommand(Str, myConnection) Dim ds As New DataSet Dim da As New OleDbDataAdapter(cmd) da.Fill(ds) Label7.Text = ds.Tables(0).Rows(0).Item("clientid") ' Response.Redirect("CrystalreportTEST_Print.aspx?C_id=" & ds.Tables(0).Rows(0).Item("clientid")) End Sub Thank you in advance
View 1 Replies
View Related
Jan 31, 2008
I'm getting the error listed above. To create this I used the wizard in VS2005 for the datagrid. The delete works but not the updating. I can't seem to find what's wrong. In the update parameters I've removed eventID and added it, neither works. Delete does work. Here's the code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="ds1" DataKeyNames="eventID"><asp:CommandField ButtonType="Button" ShowEditButton="True" ShowDeleteButton="True" /><asp:BoundField DataField="eventID" HeaderText="ID" SortExpression="eventID" ReadOnly="True" /><asp:BoundField DataField="trainer" HeaderText="trainer" SortExpression="trainer" /><asp:BoundField DataField="employeeNumber" HeaderText="Emp#" SortExpression="employeeNumber" /><asp:BoundField DataField="area" HeaderText="Area" SortExpression="area" /><asp:TemplateField HeaderText="Training Date" SortExpression="trainingDate"><EditItemTemplate><asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("trainingDate", "{0:M/dd/yy}") %>'></asp:TextBox></EditItemTemplate><ItemTemplate><asp:Label ID="Label2" runat="server" Text='<%# Bind("trainingDate", "{0:M/dd/yy}") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:CheckBoxField DataField="additionalTrainerExpected" HeaderText="Addl Trainer Expected" SortExpression="additionalTrainerExpected" ><asp:TemplateField HeaderText="Ext Trainer" SortExpression="extendedTrainer"><EditItemTemplate><asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("extendedTrainer") %>' /></EditItemTemplate><ItemTemplate><asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("extendedTrainer") %>' Enabled="false" /></ItemTemplate><HeaderStyle Font-Names="Verdana" Font-Size="Small" /><ItemStyle Font-Bold="False" HorizontalAlign="Center" /></asp:TemplateField><asp:TemplateField HeaderText="NonExt Trainer" SortExpression="nonextendedTrainer"><EditItemTemplate><asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("nonextendedTrainer") %>' /></EditItemTemplate><ItemTemplate><asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("nonextendedTrainer") %>' Enabled="false" /></ItemTemplate><HeaderStyle Font-Names="Verdana" Font-Size="Small" /><ItemStyle HorizontalAlign="Center" /></asp:TemplateField><asp:SqlDataSource ID="ds1" runat="server" ConnectionString="<%$ ConnectionStrings:TrainingClassTrackingConnectionString %>"ProviderName="<%$ ConnectionStrings:TrainingClassTrackingConnectionString.ProviderName %>"
UpdateCommand="UPDATE [trainingLog] SET [trainer] = ?, [employeeNumber] = ?, [additionalTrainerExpected] = ?, [extendedTrainer] = ?, [nonextendedTrainer] = ?, [area] = ?, [trainingDate] = ? FROM [trainingLog] WHERE [eventID] = ?">
<UpdateParameters><asp:Parameter Name="eventID" Type="Int32" /><asp:Parameter Name="trainer" Type="String" /><asp:Parameter Name="employeeNumber" Type="String" /><asp:Parameter Name="additionalTrainerExpected" Type="Boolean" /><asp:Parameter Name="extendedTrainer" Type="Boolean" /><asp:Parameter Name="nonextendedTrainer" Type="Boolean" /><asp:Parameter Name="area" Type="String" /><asp:Parameter Name="trainingDate" Type="DateTime" /></UpdateParameters>
<DeleteParameters><asp:Parameter Name="eventID" Type="Int32" /></DeleteParameters>
View 4 Replies
View Related
Feb 6, 2015
I have the got below T SQL query to fetch the matching record
DECLARE @MappingTable TABLE
(
Productname nvarchar(10),
identification_key1 int,
identification_key2 int,
identification_key3 int
[Code] .....
-- result - 'Orange'
This is an exact matching record and straight forward
Is it possible to identify the record using T SQL query based on the following scenarios
1) return the record - If all the three where conditions match
2) if record not found check and return the record where 2 columns values in the where condition match
-- Expected Result for below query: 'Orange', because 2 of the columns in where condition have matching values
SELECT Productname
FROM @MappingTable where identification_key1=1 or identification_key2 =2 or identification_key3 =1
-- result - 'Orange'
View 4 Replies
View Related
Nov 12, 2007
Good morning all,
I have searched everywhere for this and I can't find any information on it. When I use the Query Builder, in the top pane, the Filter pane, there are five columnsimension, Hierarchy, Operator, Filter Expession and Parameters.
In the dropdown for Operator, one of the choices is MDX. I cannot find any documentation on how to use this operator. I want to limit my filter to SELF_AND_AFTER, and I am hoping that this is possible using this operator. I know how to hand code it, but I have a ton of other tweaks to make to the query, so I want to use the Query Designer as much as I can.
Does anyone have any links to documentation on how to use this operator?
Thanks,
Kathryn
View 2 Replies
View Related
Aug 27, 2007
I receive the following error message when I run a distributed query against a loopback linked server in SQL Server 2005:
The Microsoft Distributed Transaction Coordinator (MS DTC) has cancelled the distributed transaction.
To resolve this problem, I was told that running a distributed query against a loopback linked server is not supported in SQL Server 2005. And I am suggested to use a remote server definition (sp_addserver) instead of a linked server definition to resolve this problem. (Although this is only a temporary resolution, which will deprecate in Katmai)
However, I run into another problem when I use the remote server definition. I receive the following error message:
Msg 18483, Level 14, State 1, Line 1
Could not connect to server 'ServerNameSQL2005' because '' is not defined as a remote login at the server. Verify that you have specified the correct login name.
Could anyone please help me out?
(I include the reproduce steps for the first error message, followed by my resolution that generates the second error message)
======
Reproduce steps for the first error message
======
On the ComputerAInstanceA instance, run the following statement to create a database and a table:
CREATE DATABASE DatabaseA
GO
USE DatabaseA
GO
CREATE TABLE TestTable(Col1 int, Col2 varchar(50))
GO
INSERT INTO TestTable VALUES (1, 'Hello World')
GO
On the ComputerBInstanceB instance, run the following statement to create a database and a table:
CREATE DATABASE DatabaseB
GO
USE DatabaseB
GO
CREATE TABLE TestTable (Col1 int, Col2 varchar(50))
GO
On the ComputerAInstanceA instance, create a linked server that links to the ComputerBInstanceB instance. Assume the name of the linked server is LNK_ServerB.
On the ComputerBInstanceB instance, create a linked server that links to the ComputerAInstanceA instance. Assume the name of the linked server is LNK_ServerA.
On the ComputerBInstanceB instance, run the following statement:
USE DatabaseB
GO
CREATE PROCEDURE InsertA AS
BEGIN
SELECT * from LNK_ServerA.DatabaseA.dbo.TestTable
END
GO
On the ComputerAInstanceA instance, run the following statement:
USE DatabaseA
GO
INSERT INTO TestTable
EXEC LNK_ServerB.DatabaseB.dbo.InsertA
GO
Then I receive the first error message.
=======
My resolution that generates the second error message
=======
On the ComputerBInstanceB instance, run the following statement:
sp_addserver 'ComputerAInstanceA'
GO
sp_serveroption 'ComputerAInstanceA', 'Data Access', 'TRUE'
GO
USE DatabaseB
GO
CREATE PROCEDURE InsertA AS
BEGIN
SELECT * FROM [ComputerAInstanceA].DatabaseA.dbo.TestTable
END
GO
On the ComputerAInstanceA instance, run the following statement:
USE DatabaseA
GO
INSERT INTO TestTable
EXECUTE [ComputerBInstanceB].[DatabaseB].[dbo].[InsertA]
GO
Then I receive the second error message.
View 1 Replies
View Related
Jun 2, 2004
I get this error when I attempt to read from a datareader using the following sql statement:
Dim mysql As String = "SELECT PayrollTrans.PayrollID, Employees.[EmpFirstName] & ' ' & " _
& " Employees.[emplastname] AS FullName, Employees.[City] & ', ' & Employees.[State] & ' ' & Employees.[zip] AS CityState " _
& " , PayrollTrans.Date, PayrollTrans.EmployeeID, PayrollTrans.RegHours, " _
& " PayrollTrans.OTHours , PayrollTrans.RegPay, PayrollTrans.OTPay, " _
& " PayrollTrans.FedTax, PayrollTrans.FICATax, PayrollTrans.MedicareTax, " _
& " PayrollTrans.ESCTax, PayrollTrans.StateTax, PayrollTrans.ESCEMPTax, " _
& " PayrollTrans.FUTATax, PayrollTrans.NetPay, Employees.EmployeeID, " _
& " Employees.Address1, Employees.Address2, Employees.SSAN, " _
& " Employees.PayType, Employees.RegPayRate, Employees.OTPayRate, " _
& " Employees.MaritalStatus, Employees.FedExemption, Employees.StateExemption, " _
& " Employees.Active, Employees.SelectforPay, Employees.PayDate " _
& " FROM PayrollTrans, Employees where PayrollTrans.EmployeeID = Employees.EmployeeID;"
my reader command list as follows:
Dim objCM As New SqlClient.SqlCommand(mysql, SqlConnection1)
Dim objDR As SqlClient.SqlDataReader
objDR = objCM.ExecuteReader
Any ideas on where I am going wrong?
Thanks in advance
View 3 Replies
View Related
May 18, 2004
I am getting a error message saying: Invalid operator for data type. Operator equals boolean AND, type equals datetime.
I traced the pointer to @gdo and @gd, they are both dates!
INSERT INTO AdminAlerts values (CURRENT_USER, 'UPDATE', getDate(), @biui, 'Updated booking, ID of booking updated: ' & @biui & ', Booking date and time before/after update: ' & @gdo & '/' & @gd & ', Room number before/after update: ' & @rno & '/' & @rn & ' and Customer ID before/after update: ' & @cio & '/' & @ci)
If I cut that two dates out it works fine.
Could someone tell me the syntax to include a date in a string :confused:
View 3 Replies
View Related
Jan 8, 2008
Hello!
I try to get a list of ConditionsVersion where Version is MAX for each ConditionsVersion.
I tried something like this (as seen on http://msdn2.microsoft.com/en-us/vcsharp/aa336747.aspx#maxGrouped):
1 List<ConditionsVersion> list = (from cv in ConditionsVersions2 group cv by cv.FKConditions into cv3 select new { 4 PKConditions = cv.PKConditions,5 FKConditions = cv.FKConditions,6 MaxVersion = cv.GroupBy.Max(cv => cv.Version)7 CTimestamp = cv.Timestamp8 }).ToList();
But it doesn't work. It would be great if someone knows why.
Thank you!
View 2 Replies
View Related
Nov 2, 2007
Well, just played a little bit with that new thing from Microsoft. Genius! Microsoft presented that step backwards as a step forward.
Say good bye to the 3-tier architecture, now any programmer, after 1 week training, will be able to put SELECT * into the source code. No more stored procedures and logic on a server. No more ugly WHERE clauses. Just SELECT * and pass all records in a loop :)
When I looked at the queries, generated by LINQ in SQL profiler, I noticed that they are generated automatically using the same pattern. It is obvious, of course, but now it would be really difficult to trace a problematic query back to the C# code. All updates to table X will look like as identical twins!
On the other side, it is not so bad. We will have soon a lot of projects, failing when they go to the production and face the real volumes of data. And a long queue of companies, crying and asking to save them. Perfect “job security�. Please, use LINQ! Port all your code to LINQ immediately (Laughing demonically like Dr. Evil)
Hm… a second thought, but what could we suggest to these companies, having performance problems with LINQ 3rd party applications, when there is no source code? Now we could at least modify some stored procedures, and with LINQ looks like the only recommendation could be “contact a developer of that application or buy more a powerful server�.
View 18 Replies
View Related
Apr 20, 2008
Is it possible to use LINQ to SQL with Report Services? If so, are there any examples, tutorials, etc.?
View 1 Replies
View Related
May 28, 2008
Is Linq a feature of sql server 2008 ?
Or is it a feature of DOt net. Visual Studio 2008 ?
View 1 Replies
View Related
May 28, 2008
Some say linq to sql leads to the death of stored procedures is it correct ?
View 4 Replies
View Related
Nov 8, 2006
Will Linq be compatible with Sql Server Everywhere without having to add additional plugins?
View 7 Replies
View Related
Dec 30, 2007
Hullo am using Asp.Net 3.5, I want to create a usercontrol that is supported to all projects to upload file into sqlserver,
the user just give the database connection string,
tablename, column name depending upon their need, here I develop the
code using LINQ technology.
I Write a class with simple format like below,
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Linq;
/// <summary>
/// Summary description for FILE_MASTER_INSERT
/// </summary>
//namespace Linq2Sql_demo_doc
//{
[System.Data.Linq.Mapping.Table(Name = "FILE_MASTER")]
public partial class FILE_MASTER
{
string Tablename;
public FILE_MASTER()
{
//
// TODO: Add constructor logic here
//
}
[System.Data.Linq.Mapping.Column(Name="filename")]
public string FileName
{
get;
set;
}
[System.Data.Linq.Mapping.Column(Name = "file_content")]
public byte[] file_content
{
get;
set;
}
[System.Data.Linq.Mapping.Column(Name = "file_id", IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
public int file_id
{
get;
set;
}
}
public class TestDB : DataContext
{
public Table<FILE_MASTER> FILE_MASTERs;
//Initializing base class constructor
public TestDB(string s) : base(s) { }
}
This
is working but, this is suitable only for single table, I expect
depending upon the user input automaticaly the tablename, column name
will change in the yellow block codes .
Is there any way to update the tablename , columnname from any other class?
Thank you. Jeyaseelan
View 1 Replies
View Related
Jan 21, 2008
I'm new to ASP/VS/Linq and I'm having a small problem.
I have one table setup in SQL Server Express 2005 through Visual Studio 2008. The table name is "Users" and has three columns (accountID, userName, email). AccountID is the primary key and set to auto incriment. I've added a couple of records by hand and it works.
I have a single form with a button, a label, and two text boxes. The button code is below. After entering some fake data that does not already exist in the database and clicking the button I get this.
Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.
I understand that it is trying to insert something into the accountID field but I don't understand why since I'm only providing a username and e-mail address to insert.
Your help is greatly appreciated.protected void Button1_Click(object sender, EventArgs e)
{
MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = from u in db.Users
where u.email == txtEmail.Text
select u;
var count = query.Count();
if (count == 0)
{
//Create a new user object.
User newUser = new User();
newUser.username = txtUsername.Text;
newUser.email = txtEmail.Text;
//Add the user to the User table.
db.Users.InsertOnSubmit(newUser);
db.SubmitChanges();
}
else
{
Label1.Text = txtEmail.Text + " already exists in the database.";
}
View 6 Replies
View Related
Jan 27, 2008
I have a supplier table with all my suppliers in it. I list them in a gridview. In this gridview, there is a link next to each record to an edit page. Below is the code for the edit page. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New orderLinqDataContext
Dim q = db.selectSupplierByID(Request.QueryString("id"))
Dim r As New System.Data.DataTable
txtFriend.Text = q(0).friendlyName
txtAdd1.Text = q(0).address1
txtAdd2.Text = q(0).address2
txtAdd3.Text = q(0).address3
txtAdd4.Text = q(0).address4
txtName.Text = q(0).supplierName
txtPhone.Text = q(0).phone
txtFax.Text = q(0).fax
txtPostCode.Text = q(0).postCode
End Sub
This causes a runtime error. The error is: "The query results cannot be enumerated more than once." and the txtAdd1.text line is highlighted.
How am I supposed to get at the data so I can fill my text boxes this way?
Thanks,
View 5 Replies
View Related
Mar 7, 2008
var query = from cloc in context.t_companylocs where (cloc.ref_company == companyid) && (cloc.street == attributes["Street"]) && (cloc.postalcode == attributes["Postalcode"]) && (cloc.country in countrylist) && (cloc.city in citylist) select cloc; attributes is a Dictionary<string, string> object.countrylist and citylist are List<string> objects.Of course the syntax above doesn't work. It's basically what I'm trying to achieve :-)A quick and dirty solution would be to just drop the two where constraints containing the "where in" statement and handle that part in the following foreach() loop.Can anyone please explain how you would do it properly?regards
View 1 Replies
View Related
Mar 12, 2008
Does anyone have a good example of how to insert data using System.Data.Linq? All the examples I've seen do something likeNorthwindDataContext db = new NorthwindDataContext();var x = new Product() {...}; db.Products.Add(x);db.SubmitChanges(); However I'm not seeing an Add method on System.Data.Linq.Table<T>. Has this changed? Could I somehow not be generating my model correctly?
View 2 Replies
View Related
Mar 20, 2008
Hello,
How can I get autogenerated value of inserted item with linq to sql?
Thanks
View 2 Replies
View Related
May 12, 2008
I would like to use LINQ to generate a sql statement that does not use LIKE, but rather uses CONTAINS. Is this possible? If not, my second question is whether or not I can parameterize a SqlCommand that uses CONTAINS. For example the following statement works just fine when I pass in the parameter via SqlCommand.Parameters.AddWithValue()SELECT * FROM [event] WHERE CONTAINS(comments, @searchTerm1)However, the following results in a variable not defined error.SELECT * FROM [event] WHERE (comments LIKE @searchTerm1)Any ideas? Thanks for your help.
View 1 Replies
View Related
May 25, 2008
Hi there,
In 2005.NET, if I used an asp:repeater, I would load the data from source and then manipulate it like so://load the data from source using a predefined connection and SQL Statement.private void LoadMyDataFromSource(){ try { connection.Open(); OleDbDataReader myReader = comm.ExecuteReader(); rptrCatList.DataSource = myReader; rptrCatList.DataBind(); myReader.Close(); } finally { connection.Close(); }} //catch the ItemDataBound event and manipulate the data how I wish before it's loaded into the Repeater.protected void rptrCatList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { int title = 4; //this is the index of the column I wish to manipulate((Label)e.Item.FindControl("lblTitle")).Text = ((IDataRecord)e.Item.DataItem).GetString(title) + ":" } }This would give me all the flexbility I ever needed. But now I wish to use linq and since the IDataRecord relies on dataReader sources, I cannot obtain the same flexbility. Can anyone point me in the right direction for obtaining the same kind of flexbility but using a linq-to-SQL dataContext? I wish to manipulate mostData that comes through from my source, so: //loadng the data in via my linq-to-sql context.private void LoadProducts() { MyDataContext db = new MyDataContext (); var all = from p in db.Products_IncontinenceStandards where p.Product_Cat == "Category1" select p; rpterCat.DataSource = all; rpterCat.DataBind(); }This is where I get stuck because, even though I can still capture the ItemDataBound event since I have databound the Repeater to the linqSource, I can't access the individual fields (or this is what I think I can't do!), Does anyone know how to relate to this so I can create the same effect? Many Thanks,Nathan Channon
View 4 Replies
View Related
Apr 24, 2008
Hi,
I am beginner in SQL Server So excuse me if my question is stange for you.
I have to work on an sql server 2005. I need to extract data from this server in XML file. I have look at a lots of thing and I find two solutions:
- Use SSIS
- Create a home made solution with LINQ in c#
Clearly I do not have enouth experience to see with solution are the most available? Which are the things required to use those solutions?
Thanks
View 12 Replies
View Related