Failed to convert parameter value from a Guid to a String - c#

I am at the end of my knowledge and googled for the answer too but no luck :/
Week ago everything worked well.
I did a revert on the repository, recreated the tableadapter etc... nothing helped.
When I try to save in my application I get an SystemInvalidCastException at this point:
PersonListDataSet.cs:
partial class P_GroupTableAdapter
{
public int Update(PersonListDataSet.P_GroupDataTable dataTable, string userId)
{
this.Adapter.InsertCommand.Parameters["#userId"].Value = userId;
this.Adapter.DeleteCommand.Parameters["#userId"].Value = userId;
this.Adapter.UpdateCommand.Parameters["#userId"].Value = userId;
return this.Update(dataTable); **<-- Exception occurs here**
}
}
Everything is stuck here because a Guid - and I checked the datatable preview with the magnifier tool its really a true Guid in the column of the datatable - can not be converted to a string ??? How can that happen?

It's the other way around. Your userId is a string and you need a GUID value for your parameters:
Parameters["#userId"].Value = new Guid(userId);
Provided UserId is in one of the supported formats for a GUID. The constructor supports many formats.
Edit, based on comments below:
It turns out that you are asking how to run a select statement like:
SELECT ....
WHERE '{BB6DFF45-FDA7-4155-86D0-0CBF129A9104}' = `domainname\\jondoe`
I think you should re-check your datamodel and find a solution.

Have you tried:
this.Adapter.InsertCommand.Parameters["#userId"].Value = new Guid(userId);
this.Adapter.DeleteCommand.Parameters["#userId"].Value = new Guid(userId);
this.Adapter.UpdateCommand.Parameters["#userId"].Value = new Guid(userId);
Hope it helps!!!

Related

LINQ Expression - Returning a UserID based on the Name Specified in a LinkLabel

Please, I am trying to access my database to get access to a user id. But when i try accessing, what gets returned is 0. Initially, i had issues figuring out how to change this SQL statement (SELECT user_id FROM users WHERE firstname = 'Godymn') to LINQ. But i later found that i could use :
var result = users.Where(x=>x.firstname == "Godymn").Select(x=>x.userid);
So far, when i tried to use the query in my code, it returns a 0. But what i need is to return the user id based on the name specified in the linkLabel. I have not been able to figure out why its not working.
Will appreciate any help.
Here is my code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel())
{
result = db.users.Where(x => x.firstname == link).Select(x => x.user_id).FirstOrDefault();
}
return result;
}
Here is the button i used to check the content of what got returned.
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Good Afternoon Godymn.
Here are some possible scenarios:
1 - The user name Godymn does not exist in the database
2 - The user_id is 0.
Try checking this 2 scenarios.
After that, you could change your approach to a more "debug friendly" level.
var result = db.users.First(f => f.firstname == link);
Then, check if result is null. If it is null, the name was not found in the database.
If it is not null, check if the result is 0.
Why this approach: This way, you can tell if the problem is when you are searching for the user or when you are binding the value of Id.
I can't comment, i'm sory, but first of all i'll try this:
var foo = db.users.Select(x => x).ToList();
then you can investigate your result like this
i suppose you try get wrong data (or wrong structure)
when i stuck i do this:
Or maybe you can attach your structure of object?
So yeah, I was able to fix the bug. The problem was with the linkLabelPartner.Text as Chris Dunaway rightly said. As soon as he mentioned if the linklabel contains only firstname, I just knew that was the missing piece. This holds firstname and lastname and I only accounted for just firstname. Hence the value returned remains at 0. So, all I had to do was to concatenate both firstname and lastname which solved the issue. So, yeah the query I used initially was right.
Here is the code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel ())
{
result = db.users.Where(x => x.lastname + " " + x.firstname == link ).Select(x => x.users).FirstOrDefault();
}
return result;
}
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Many thanks everyone for your suggestions, appreciate.

WPU SQLite.Net.SQLiteConnection.Query encoding issue

I have a encoding problem with the Query of SQLite.Net. Everything works fine if i only use the column names in the SQL String, but if i write the SQL on my own, every special char like ä,ü,ö,ß will not be encoded correctly.
Here are two easy examples, one working, one not.
public class ass {
[PrimaryKey, AutoIncrement]
public int _id { get; set; }
[MaxLength(255)]
public string sortname { get; set; }
}
dbConn = new SQLiteConnection(new SQLitePlatformWinRT("testpasswort"),DB_PATH);
dbConn.CreateTable<ass>(SQLite.Net.Interop.CreateFlags.None);
//add a test entry with special chars
ass asss = new ass();
asss.sortname = "oe=öae=äszett=ß";
dbConn.Insert(asss);
//now select the test entry to an ass object
List<ass> getass = dbConn.Table<ass>().ToList<ass>();
//the list is filled and sortname = "oe=öae=äszett=ß"
//now fake a object with
List<ass> sqlass = dbConn.Query<ass>("SELECT 'oe=öae=äszett=ß' as sortname FROM ass").ToList<ass>();
//the List is filled and sortname = "oe=�ae=�szett=�"
I know the query is useless and the following will work:
List<ass> sqlass = dbConn.Query<ass>("SELECT sortname as FROM ass").ToList<ass>();
But the problem is, that the .Query funktion have a encoding issue, this will NOT work:
List<ass> sqlass = dbConn.Query<ass>("SELECT sortname FROM ass WHERE sortname LIKE '%ä%'").ToList<ass>();
But this will work:
List<ass> sqlass = dbConn.Query<ass>("SELECT sortname FROM ass).ToList<ass>().Where(v => v.sortname.Contains("ä"));
everytime i have any special char in the sqlcode it will not work, this is fatal for my needs, because i have a lot of replace(column,find,replace) statements and all of them failed if the find or replace String contains any ü,ö,ä [...]
Did anyone know how to sove this?
A possible solution would be to use #params instead of direct string request. And use the UTF-8 encoding pragma, which you can also use to check your existing database encoding. A helpful description for this issue can be found here.

SQLite exception deleting row using sqlite-net

I got tired to search so here it goes my first SO question hoping someone had the same problem and can help me
Goal
I am trying to store my application data with a SQLite database
Application description
Windows 8 app C# XAML with local SQLite database using SQLite for Windows Runtime Extension and sqlite-net library
Table definition
public class Product {
private int _id;
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int ID
{
get { return _id; }
set { _id = value; }
}
private string _date;
public string DATE
{
get { return _date; }
set { _date = value; }
}
private string _desc;
public string DESC
{
get { return _desc; }
set { _desc = value; }
}
}
Problem1
public int Insert (object obj) description says the following:
Inserts the given object and retrieves its auto incremented primary key if it has one.
However everytime I insert a row it return 1. I can sucessfully insert with a auto-incremet ID but somehow it does not return me its ID. Why?
Problem 2
I can insert new rows but not delete them
Working around problem 1 to get last row generated ID, I try to delete rows but with no success.
See this example test that always fails:
using (var db = new SQLiteConnection(Path.Combine(_path, _dbname)))
{
var p1 = new Product() { DESC = "insert1", DATE = DateTime.Now.ToString() };
db.Insert(p1);
p1.ID = 1;
var p2 = new Product() { DESC = "insert2", DATE = DateTime.Now.ToString() };
// I am sure that this row is getting ID 2, so it will not have a wrong ID
p2.ID = 2;
db.Insert(p2);
var p3 = new Product() { DESC = "insert3", DATE = DateTime.Now.ToString() };
db.Insert(p3);
p3.ID = 3;
db.Delete<Product>(p2);
}
As you can see I try to insert 3 rows and delete the second one. The rows are inserted but I get the following SQLite.SQLiteException exception:
unable to close due to unfinalized statements or unfinished backups
Why? I don't open other connections before and after that.
Thanks in advance
Solved
Problem 1
+1 and thanks for #Bridgey for pointing out that function does not match it description and for the relevant search
The function does not return ID as it says but it defines the object ID. So when I insert a new Product, Product.ID will have last inserted ID.
Problem 2
I changed db.Delete<Product>(p2); to db.Delete(p2); and now it works. SQLite-net correctly identify the row as Product. I still don't know why the unable to close due to unfinalized statements or unfinished backups exception was happening. If someone knows why tell me please.
I think for problem 2, the issue is that you are passing the Product object as the parameter for the Delete method. The documentation says: Deletes the object with the specified primary key. I think the following should work:
db.Delete<Product>(p1.ID);
Regarding problem 1, the code of the Insert method of the sqlite-net package ends:
var count = insertCmd.ExecuteNonQuery (vals);
if (map.HasAutoIncPK) {
var id = SQLite3.LastInsertRowid (Handle);
map.SetAutoIncPK (obj, id);
}
return count;
As you can see, count is returned, even if id is set.
EDIT: Actually, according to the author this is deliberate.
"Insert returns the number of rows modified. The auto incremented columns are stored in the object. Please see the doc comments."
https://github.com/praeclarum/sqlite-net/issues/37

Failing to write to database using entity framework ( edmx )

As the title says, I have a problem writing to local database. I generated a edmx Model from this, and I can easily read from it.
EDMXNS.TOWDataBasev1Entities db = new EDMXNS.TOWDataBasev1Entities();
var query = from p in db.Accounts select p;
foreach (EDMXNS.Accounts s in query)
Console.WriteLine(s.AccountName);
That works fine. However when I try to write to the database, nothing happens. I do not get any errors, exceptions etc. I figure, since I can read from the database, that it's not a connection problem.
Here is the code i have for writing.
EDMXNS.TOWDataBasev1Entities db = new EDMXNS.TOWDataBasev1Entities();
EDMXNS.Accounts acc = new EDMXNS.Accounts();
acc.AccountID = 1;
acc.AccountName = "testuser";
acc.AccountPW = "testpw";
acc.PersonDataID = 0;
db.AddToAccounts(acc);
db.SaveChanges();
It is worthwhile to meantion that my Accounts.AccountID has identity/autoincrement, but I have tried both setting it to the next known value, or simply not setting it at all.
Do anyone have an idea as to what might cause this problem?
EDIT: I also tried to remove the custom name space, delete all records of the database and reimport it all.
Removing the custom tool name space, results in errors like these:
Ambiguity between 'TOWServer.Accounts.AccountName' and 'TOWServer.Accounts.AccountName'
Which doesnt tell me anything.
Reimporting everything now gives me an exception:
"Unable to load the specified metadata resource"
I've always use this format when adding records with EF, Try following this format:
using (MovieStoreEntities context = new MoveStoreEntities())
{
try
{
context.Movies.AddObject(new Movie() { MovieID = 234,
Title = "Sleepless Nights in Seattle", Quantity = 10 });
context.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
}
}

help inserting new row into a db using linq

Here is a snippet of my code:
else
{
SubCategory subCat = new SubCategory
{
SubCategoryName = name,
Active = false,
CategoryID=Convert.ToInt32(ddlCategory.SelectedValue)
};
db.SubCategories.InsertOnSubmit(subCat);
}
db.SubmitChanges();
The following line is causing an error:
CategoryID=Convert.ToInt32(ddlCategory.SelectedValue)
I have confirmed that the SelectedValue in my DDL is an int, and that the database is expecting an int, so I don't understand why asp.net gives me a YSOD saying "Input string was not in a correct format."
If I assign CategoryID a number manually, it works.
EDIT: The problem was because I was populating the drop down list in my code behind and I didn't wrap it in a (!IsPostBack). So it was destroying the list, repopulating it and setting the index at 0 each time on post back.
so try this then
else
{
int cat = Convert.ToInt32(ddlCategory.SelectedValue);
SubCategory subCat = new SubCategory
{
SubCategoryName = name,
Active = false,
CategoryID = cat
};
db.SubCategories.InsertOnSubmit(subCat);
}
Where does ddlCategory come from? What's the value of ddlCategory.SelectedValue? When this gets run? Clearly it's not a valid integer-representing string at this point in time.
Maybe try
Int.Parse(ddlCategory.SelectedValue);
is the categoryID foreign key for another table? if yeah then try to pull the Category object and then assign it to the subCat.Category and see if it works (the relation must be set in the DBML designer)
one last thing: when exactly it throws the exception?

Categories

Resources