user3209554 user3209554 -4 years ago 81
C# Question

ado.net "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 C#.net
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");
con.Open();

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);
cmd.Parameters.AddWithValue("win",0);
cmd.Parameters.AddWithValue("win",0);
cmd.ExecuteNonQuery();

con.Close();


** the
session
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')

With

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