SQL Server 2008 (version 10.50.2550).
I have a select query to return a single column of type uniqueidentifier.
I want to get this into a C# variable of type Guid.
All of the following methods result in exceptions.
reader is of type SqlDataReader.
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
Guid guid = reader.GetGuid(reader.GetOrdinal("integ_schemehistoryId")); //1
Guid guid = Guid.Parse((string)reader["integ_schemehistoryId"]); //2
Guid guid = (Guid)reader["integ_schemehistoryId"]; //3
Guid guid = new Guid((string)reader["integ_schemehistoryId"]); //4
Guid guid = Guid.Parse(reader["integ_schemehistoryId"].ToString()); //5
}
}
Error for 1:
System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting from a character string to uniqueidentifier.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.HasMoreRows()
at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
at System.Data.SqlClient.SqlDataReader.Read()
at Simego.DataSync.DynamicColumns.DataSourceRowOverride.get_EpochSchemeHistoryID()
Error for 2:
System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'.
at Simego.DataSync.DynamicColumns.DataSourceRowOverride.get_EpochSchemeHistoryID()
Error for 3:
System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting from a character string to uniqueidentifier.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.HasMoreRows()
at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
at System.Data.SqlClient.SqlDataReader.Read()
at Simego.DataSync.DynamicColumns.DataSourceRowOverride.get_EpochSchemeHistoryID()
Error for 4:
System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'.
at Simego.DataSync.DynamicColumns.DataSourceRowOverride.get_EpochSchemeHistoryID()
Error for 5:
System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting from a character string to uniqueidentifier.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.HasMoreRows()
at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
at System.Data.SqlClient.SqlDataReader.Read()
at Simego.DataSync.DynamicColumns.DataSourceRowOverride.get_EpochSchemeHistoryID()
There is something wrong either with your data or your SQL. The first and third approaches should work - personally I'd use the first form, as it's the clearest in my view.
But look at the stack trace:
...
at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
at System.Data.SqlClient.SqlDataReader.Read()
at Simego.DataSync.DynamicColumns.DataSourceRowOverride.get_EpochSchemeHistoryID()
Note that it's the Read() call which is failing, not GetGuid or the indexer.
My guess is that your property is being fetched several times, and sometimes it works - which is why you were getting a cast exception in your second approach - but for some rows, it fails due to some problem with the data or the SQL. As we've no idea where your data is coming from, we can't help you beyond that diagnosis, but that's where you should look next.
As the other answers suggest, you should try:
Guid guid = Guid.Parse(reader["integ_schemehistoryId"].ToString())
You might also want to check your stored procedures and your table, there may be something wrong there.
That error is being generated from SQL. In other words there something wrong with you SQL command text. Not your c# code.
Have you tried:
Guid guid = new Guid((string)reader["integ_schemehistoryId"]);
Try by using Guid.Parse method
Guid guid = return Guid.Parse((string)reader["integ_schemehistoryId"]);
In Oracle database:
"ID" RAW(16) DEFAULT SYS_GUID() NOT NULL ENABLE,
This code worked for me:
using (IDataReader dr = ... )
{
while (dr.Read())
{
var Id = new Guid();
if (!(dr["ID"] is DBNull)){
Id = new Guid((byte[])dr.GetValue(dr.GetOrdinal("ID")));
}
}
dr.Close();
}
object val = reader[0];
Guid g;
if ( Guid.TryParse(val, out g) )
{
return g;
}
else
{
Trace.WriteLine("Error: " + g == null ? string.Empty : g.ToString());
}
Related
This is what I want to use;
string insertQuery = #"insert into userinfo (UserName, FirstName, LastName,
E-mail, Password, Country)
values ( '" + uname + "', '" + fname +
"','" + lname + "', '" + email + "')";
where every one of the variables in between the + are string variables with values in them. but when I run this command, I get some incorrect syntax error.
This is the new error i get;
errorSystem.Data.SqlClient.SqlException (0x80131904): String or binary
data would be truncated. The statement has been terminated. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
Registration.RegistrationPage.Button1_Click1(Object sender, EventArgs
e) in c:\Users\kristhnen.jagambrum\Documents\Visual Studio
2012\Projects\Registration\Registration\RegistrationPage.aspx.cs:line
50 ClientConnectionId:6d959e49-5b62-43be-b202-76f7eb1fbd2c
It's very good that you asked - the code that you show is a perfect illustration of two security issues in a single line:
The table structure is an illustration of what lets hackers steal user passwords.
The C# code is what makes SQL injection attacks possible.
Fixing the first problem is hard: you need to learn about password hashing and how to store user info in DB. Here is a Q&A that will help: Best way to store passwords in DB
The second problem is easier - all you need is replacing the injected values with parameter names, and then adding the values for each parameter name:
... // Create SQL command, then set its text
command.CommandTest = #"INSERT INTO userinfo (
UserName, FirstName, LastName, E-mail, Password_hash, Password_salt, Country
) VALUES ( #uname, #fname, #lname, #email, #pwd_hash, #pwd_salt, #country)";
// Bind the parameters
command.Parameters.Add(new SqlParameter("#uname", uname));
command.Parameters.Add(new SqlParameter("#fname", fname));
... // ...and so on
command.ExecuteNonQuery();
The answer is you don't, because it is a bad idea. You should be using SQlCommand instead
Check This out,and there are plenty of examples of how to use it. Appending variables in the way you doing is considered to be the mistake number 3 in the list of 25 most dangerous programming mistakes.
Try something like this, and not use direct parameter in sql command
public const string InsertStmtUsersTable = "insert into userinfo (UserName, FirstName, LastName,
[E-mail], Password, Country) values (#UserName, #FirstName, #LastName,
#[E-mail], #Password, #Country) "
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(InsertStmtUsersTable, conn))
{
command.CommandType = CommandType.Text;
command.Parameters.Add(new SqlParameter("username", userNameString));
command.Parameters.Add(new SqlParameter("FirstName", FirstNameString));
// Rest of your Parameters here
command.ExecuteNonQuery();
}
}
I am trying to insert data in a table (say feedback) with columns from(int) and Message(Varchar(MAX)) via c# code but it is continuously annoying me with errors. Please help, I am desperate.
Table description:
From int,Message Varchar(max)
Code I'm using:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleConnectionString"].ConnectionString);
con.open;
string query="insert into Feedback (From,Message) values(#frm,#msg)";
SqlCommand comm = new SqlCommand(query, con);
comm.Parameters.AddWithValue("#frm", Convert.ToInt32(TextBoxid.Text));
comm.Parameters.AddWithValue("#msg",TextBoxFeedBack.text);
comm.ExecuteNonQuery();
con.Close();
The Error I'm getting is
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near
the keyword 'From'. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, DbAsyncResult result) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult
result, String methodName, Boolean sendToPipe) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
_Default.Button1_Click(Object sender, EventArgs e) in c:\Users\Ajaz\Documents\Visual Studio
2010\WebSites\WebSite26\Default.aspx.cs:line 29
I'm guessing there's error related to data mismatch. Please help.
Thanks
FROM is a reserved keyword in TSQL. You should use it with square brackets like [FROM]
string query="insert into Feedback ([From],Message) values(#frm,#msg)";
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Also use using statement to dispose your SqlConnection like;
string query = "insert into Feedback ([From],Message) values(#frm,#msg)";
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleConnectionString"].ConnectionString))
{
SqlCommand comm = new SqlCommand(query, con);
comm.Parameters.AddWithValue("#frm", Convert.ToInt32(TextBoxid.Text));
comm.Parameters.AddWithValue("#msg",TextBoxFeedBack.text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
}
"From" is the reserved word. Surround it by square brackets:
string query="insert into Feedback ([From],Message) values(#frm,#msg)";
Well, the word FROM is a well known keyword in any SQL language existing in the world. If you want to use it (very bad move) then you need to encapsulate it in square brackets
string query="insert into Feedback ([From],Message) values(#frm,#msg)";
Again, don't do that, change the name of the column before having to much code to change.
Otherwise you will have this problem for the lifetime of your app.
I'm trying to read in from a local database and create and return an object. my code works fine the first 3 times through the loop that calls it and then fails giving me an error: Arithmetic overflow error converting varchar to data type numeric. I've done plenty of debugging and the error is being thrown at reader.Read(). To my knowledge I'm not converting anything there, and all my research has turned up completely different sources for this error. any help would be greatly appreciated.
System.Data.SqlClient.SqlDataReader reader;
/*Initialize Variables*/
using (SqlCommand cmd = GetCommand("SELECT * FROM tblInventoryItem where InvoiceID = " + InvoiceNumber))
{
//Do Work...
try
{
cmd.Connection.Open();
reader = cmd.ExecuteReader();
InventoryItem i;
NItem ni;
InventoryDataRepository2 idr = new InventoryDataRepository2();
while (reader.Read())
{
//Create an instance of the object....
i = new InventoryItem();
ni = new NItem();
ni.ItemNumber = (string)reader["ItemNumber"];
InventoryItem invitem = (InventoryItem)idr.GetItem(ni.ItemNumber);
ni.Title = invitem.Item.Title;
ni.Model = invitem.Item.Model;
ni.RetailPrice = invitem.Item.RetailPrice;
ni.WholesalePrice = invitem.Item.WholesalePrice;
i.Item = ni;
i.Quantity = Convert.ToInt32(reader["Quantity"]);
allItems.Add(i);
}
EDIT: stacktrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
at System.Data.SqlClient.SqlDataReader.Read()
at NeweggDistributor.InventoryItemDataRepository.GetAllItemsInInvoice(String InvoiceNumber) in c:\Users\AJ\Documents\Visual Studio 2012\Projects\NeweggDistributor\NeweggDistributor\InventoryItemDataRepository.cs:line 90
Arithmetic overflow error converting varchar to data type numeric.
I agree with Eric J. i don't believe Reader.Read() would throw such an error. What i see is likely to throw such an error tho is if the Quantity field in the DB is a string and cannot be converted to an integer, or if it is null in the DB because null cannot be converted to any integer. other possibilities are the RetailPrice and WholesalePrice fields. Perhaps you can comment out those lines and make sure you don't get the same error when they are commented out. then you can uncomment each field one at a time, testing that each field one new field at a time.
My first guess is that i.Quantity = Convert.ToInt32(reader["Quantity"]); is trying to convert a varchar field into an int and the varchar string is not numeric. I hardly ever use Convert.ToInt32 or C# casting for situations like this because they can throw unexpected nasty errors. I create a separate method that converts what i want, and i pass it a default value that is returned if the conversion cannot be performed. Thus i use a 'defaultValue' parameter in my conversion methods.
Your query is
SELECT *
FROM tblInventoryItem
WHERE InvoiceID = 1234
My guess is that InvoiceID in the database is a varchar field.
This means that you are comparing an integer with a varchar in the where clause. Implicit conversions changes your query to
SELECT *
FROM tblInventoryItem
WHERE CONVERT(int, InvoiceID) = 1234
You will get an error if any InvoiceID in the database contains something which will not fit into an integer.
The arithmetic overflow error make the most probable cause an invoiceid > 2147483648
Note that the error will not happen if your InvoiceNumber is also to big for an integer.
SELECT *
FROM tblInventoryItem
WHERE InvoiceID = 5000000000
will work because it is changed to
SELECT *
FROM tblInventoryItem
WHERE CONVERT(bigint, InvoiceID) = 5000000000
The solution is of course to use parameters
command.CommandText = #"SELECT * " +
#"FROM tblInventoryItem " +
#"WHERE InvoiceID = #InvoiceNumber";
command.Parameters.Add("#InvoiceNumber", SqlDbType.VarChar).Value = InvoiceNumber;
(You can also use a parameter of type SqlDbtype.BigInt if you are sure InvoiceID only contain numbers)
I have a weird error when trying to call .SaveChanges() in Entity Framework.
I'm trying to save an Order like this
public void SaveOrder(UserDTO user, ArticleDTO article, PriceDTO price, decimal amount)
{
//Get the order with type cart. If no order exist create a new order with type cart.
var order = _orderRepository.GetCartOrderForCustomer(user.Customer.CustomerREFID);
if (order == null)
{
order = new Order()
{
CustomerREFID = user.Customer.CustomerREFID,
CreateDate = DateTime.Now,
OrderType = OrderType.Cart
};
_orderRepository.Add(order);
_orderRepository.UnitOfWork.Commit();
}
}
Sure its working fine when I'm only calling this method. But when I'm calling another method before this method then I get errors.
The before method just fetch articles and prices.
public IEnumerable<Article> GetArticlesByCategory(int categorySection, int headCategory, string customerREFID)
{
var currentUnitOfWork = this.UnitOfWork as MainBCUnitOfWork;
//Linq query without keys.
var result = (from a in currentUnitOfWork.Articles
join cat in currentUnitOfWork.Categories on a.CategoryID equals cat.CategoryID
join cf in currentUnitOfWork.CategoryReferences on cat.ID equals cf.CategoryID
join c in currentUnitOfWork.Customers on a.Lagstalle equals c.LagStalle
where cf.RefID == categorySection && cat.HuvudKat == headCategory && c.CustomerREFID == customerREFID
select a).ToList();
var artnumbers = result.Select(a => a.Number).ToList();
var prices = currentUnitOfWork.Prices.Where(p => artnumbers.Contains(p.ArtNr) && p.FtgNr == customerREFID).ToList();
Parallel.ForEach(result, a =>
{
a.Prices = prices.Where(p => p.ArtNr == a.Number).ToList();
});
return result.ToList();
}
So when calling SaveOrder I get this error :
{System.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_dbo.PriceArticles'. Cannot insert duplicate key in object 'dbo.PriceArticles'. The duplicate key value is (6653, 1).
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
ClientConnectionId:dfc62e28-3751-4a54-89f4-5fa8195cab2a}
This table and get has nothing to do with Order table ? Why does Entity Framework commit other tables when I only add a new Order ?
How do I work around this ?
I'm trying to execute an Insert statement, but keep getting a Invalid object name error.
Here's my code:
public string addNewComment(int userID, int pageID, string title, string comment)
{
string query = "INSERT INTO dbo.nokernok_kommentarer (userID, pageID, commentTitle, comment) " +
"VALUES ("+ userID +", "+ pageID +", '"+ title +"', '"+ comment +"')";
adapter.InsertCommand = new SqlCommand(query, connection);
//ExecuteNonQuery retuens number of rows affected
int numRows = adapter.InsertCommand.ExecuteNonQuery();
return numRows.ToString();
}
And here is my error message:
System.Data.SqlClient.SqlException:
Invalid object name
'dbo.nokernok_kommentarer'. at
System.Data.SqlClient.SqlConnection.OnError(SqlException
exception, Boolean breakConnection) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj) at
System.Data.SqlClient.TdsParser.Run(RunBehavior
runBehavior, SqlCommand cmdHandler,
SqlDataReader dataStream,
BulkCopySimpleResultSet
bulkCopyHandler, TdsParserStateObject
stateObj) at
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String
methodName, Boolean async) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult
result, String methodName, Boolean
sendToPipe) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at
development.DAL.nokernokDAL.addNewComment(Int32
userID, Int32 pageID, String title,
String comment) in
C:\Inetpub\wwwroot\naaf\DAL\nokernok.cs:line
49
Can anyone help me figure out why I get this error?
UPDATE
I should be using the correct database, because the following query works:
public DataSet getSchools(string countyCode)
{
DataSet ds = new DataSet();
string query = "SELECT * FROM nokernok_skoler WHERE kommunekode LIKE '" + countyCode.Substring(0, 2) + "%' ORDER BY enhetsnavn";
adapter.SelectCommand = new SqlCommand(query, connection);
adapter.Fill(ds);
return ds;
}
My connection string looks like this:
SqlConnection connection = new SqlConnection();
SqlDataAdapter adapter = new SqlDataAdapter();
// class constructor
public nokernokDAL()
{
connection.ConnectionString = EPiServer.Global.EPConfig["EPsConnection"].ToString();
connection.Open();
}
You're probably in the wrong database. Include an initial catalog in your connection string:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername; ...
^^^^^^^^^^^^^^^^^^^^^^^^^^
Or specify a three part name:
INSERT INTO myDataBase.dbo.nokernok_kommentarer
^^^^^^^^^^
From the error message, it would appear that the table dbo.nokernok_kommentarer doesn't exist in your database, or it isn't a table and is thus not updatable.
Have you checked that:
You're connecting to the server you think you're connecting to?
You're connecting to the database you think you're connecting to?
You're specifiying the correct catalog (or whatever it's currently called =) i.e. Are you sure it should be dbo. and not somethingElse.?
The table dbo.nokernok_kommentarer exists?
If you copy the SQL out from your code and run it in something like SQL Server Management Studio, does it work without error there?