help inserting new row into a db using linq - c#

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?

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.

Linq 2 Sql - Getting the Id of the newly inserted row - Not working?

Lets assume this code:
Classified classified = new Classified();
classified.Title = title;
classified.IsActive = true;
user.Classifieds.Add(classified);
dContext.SubmitChanges();
Response.Redirect(string.Format("/classifieds/post/?cid=", classified.Id));
Well, classifiedId has no value, Since i am redirected to http://www.mysite.loc/classifieds/post/?cid=
anyone?
The problem is in your string format:
Response.Redirect(string.Format("/classifieds/post/?cid={0}", classified.Id));
You forgot to include the {0} so it knows where to place the ID.

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

Why does adding this line mess up my NHibernate mapping?

I have a very simple ClassMap
public class ContentMap : ClassMap<Content>
{
public ContentMap()
{
// Basic property mapping
// Parent property mapping
References(x => x.Category).Column("CategoryId");
}
}
Using this, my mappings work perfectly fine and the Category property is not null.
If I try to add this line below the first reference
References(x => x.LastActive).Column("LastActiveSubCategoryId");
My mappings go wrong.
If LastActiveSubCategoryId is null, Category maps fine. If it is not null, LastActiveSubCategoryId will be set but then CategoryId is null.
The actual properties themselves are simple
public virtual Category Category { get; set; }
public virtual SubCategory LastActive { get; set; }
There is nothing complex in the Category or SubCategory mappings either. They look very similar to the ContentMap class (with only one reference line)
Any idea what would cause this behavior? Can I only use one Reference?
Update
I've looked at the SQL and this is what appears to be happening, hopefully someone can help me understand why.
The Content entity gets inserted into the database just fine with the CategoryId and LastActiveSubCategoryId null.
The Category entity gets inserted and then an update statement updates the Content, only updating the CategoryId field and nothing else.
If there was no SubCategory, everything would be fine at this point.
If there is a SubCategory, then a few statements later it is inserted and then the Category gets updated. In the update statement a few different values are being modified (some that don't need to be as they haven't changed since the insert), including the CategoryId and SubCategoryId. Except now CategoryId is null and LastActiveSubCategoryId is not.
So why would CategoryId be null on the update?
Update 2
The code I'm using to actually insert the objects is just for some basic tests at this point. These are the relevant bits of code:
Category category = new Category();
dao.Save(category);
Content content = new Content();
category.AddContent(content); // Adds it to a list, like in the tutorial mBotros posted
dao.Save(Content);
SubCategory subCategory = new SubCategory();
content.AddSubCategory(subCategory);
dao.Save(subCategory);
// On the Content class
public virtual void AddSubCategory(SubCategory subCategory)
{
SubCategories.Add(subCategory);
LastActive = subCategory;
}
There is a circular reference in your database schema, which can make inserting rows tricky.
Content references SubCategory, and SubCategory references Content. If you were to try to insert rows using plain old SQL, you would not be able to do this:
/* this line does not work because SubCategory 2 does not exist yet */
insert into Content (Id, LastActiveSubCategoryId) values (1, 2);
insert into SubCategory (Id, ContentId) values (2, 1);
You would instead have to do something like this:
insert into Content (Id, LastActiveSubCategoryId) values (1, null);
insert into SubCategory (Id, ContentId) values (2, 1);
update Content set LastActiveSubCategoryId = 2 where Id = 1;
You need to keep this in mind when you are persisting your NHibernate entities. Modify AddSubCategory to not set LastActive. First save the two entities, then close the loop.
// ... code to save Category and Content, then...
SubCategory subCategory = new SubCategory();
content.AddSubCategory(subCategory); // modified to *not* set LastActive
dao.Save(subCategory);
content.LastActive = subCategory;
dao.Update(content);
You mention a LastActiveId that is not in the code you've shown.
Are you by chance trying to map a column as both a Reference and a scalar Property?
Update: either your code snippet is still incomplete, or you're missing the transaction/flush that will cause the updates to happen. Also, do you have both a collection (not shown) called SubCategories and a property called LastActive?

Failed to convert parameter value from a Guid to a String

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!!!

Categories

Resources