Custom data annotation syntax error

Asked at 2017-01-10 04:16:07Z
  • 5 Subscribers

I've created a custom data annotation to inform the user that a duplicate SKU has been entered. The data annotation is as follows:

[Remote("doesSKUExist", "Products", HttpMethod = "POST", ErrorMessage = "SKU already exists. Please enter a different SKU.")]
public string SKU { get; set; }

In the ProductsController I have the following:

    public JsonResult doesSKUExist(string Sku)
        string conStr = @"Data;Initial Catalog=CMSDatabase;Integrated Security=False;User ID=dwight;Password=Fatboy99!;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        SqlConnection sqlconn = new SqlConnection(conStr);

        SqlCommand does_SKU_exist = new SqlCommand("SELECT SKU FROM [Product] WHERE([SKU] = @SKU", sqlconn);
        does_SKU_exist.Parameters.Add("SKU", SqlDbType.VarChar).Value = Sku;
        var sku = does_SKU_exist.ExecuteScalar();
        return Json(sku == null);

Currently, I am getting an error at line:

var sku = does_SKU_exist.ExecuteScalar();

"Incorrect syntax near @SKU" Can anyone help with this?

1 answers in total

un-lucky Posted at 2017-01-10 04:18:33Z

You forgot to close the ) after the where clause, but actually there is no need for ( and ) in your case: the SqlCommand initialization should be like the following:

SqlCommand does_SKU_exist = new SqlCommand("SELECT SKU FROM [Product] WHERE [SKU] = @SKU", sqlconn);

You have to do a small change while adding parameter as well, that is :

does_SKU_exist.Parameters.Add("@SKU", SqlDbType.VarChar).Value = Sku;

Answer this questsion