user3209554 user3209554 -4 years ago 81
C# Question "No mapping exists from object type xo.Player to a known managed provider native type."

I'm trying to connect a DB to an XO game I made in
now I already got a table and I'm trying to insert values into it and i get an error

This is my code:

SqlConnection con = new SqlConnection
(@"Data Source=.\SQLExpress;Initial Catalog=ExampleDB;Integrated Security=True");

SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;

cmd.CommandText = "insert into XOhalloffame (PlayerName ,Winnings, Losses) values ('@name', '@win', '@lose')";
cmd.Parameters.AddWithValue("name", Session["player1"]as Player);


** the
of player1 is an asp textbox, i want the player to insert the name dynamicly.

the Error is:

No mapping exists from object type xo.Player to a known managed provider native type.

Answer Source

In your INSERT string, replace the following

values ('@name', '@win', '@lose')


values (@name, @win, @lose)

You do not need apostrophes when declaring scalar variables in a SQL query.

Also you need to put the @ symbol in your cmd.Paramaters.AddWithValue() calls like so:

cmd.Parameters.AddWithValue("@Name", yourValue);
cmd.Parameters.AddWithValue("@Win", yourvalue);
cmd.Parameters.AddWithValue("@Lose", yourValue);

To address the error however, I think you are trying to pass a Player object into your query, when you really just want the Player's name. Without seeing your Player implementation it is hard to say but you want something like this.

cmd.Parameters.AddWithValue("@name", Session["player1"].Text);

The error is telling you that a Player is not a known type to SQL and thus cannot be inserted into a column with (likely) varchar typing. You just need to input the actual Text from the text box, or the Name property of your Player object.

I realize this answer covers more than your question, but you will likely run into more errors if you don't fix the syntax.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download