自定义数据注释语法错误

时间:2017-01-10 04:16:07

标签: c# sql data-annotations

我已创建自定义数据注释,以通知用户已输入重复的SKU。数据注释如下:

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

在ProductsController中,我有以下内容:

[HttpPost]
    public JsonResult doesSKUExist(string Sku)
    {
        string conStr = @"Data Source=cmsapirontech.database.windows.net;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);
        sqlconn.Open();
        does_SKU_exist.Parameters.Add("SKU", SqlDbType.VarChar).Value = Sku;
        var sku = does_SKU_exist.ExecuteScalar();
        return Json(sku == null);
    }

目前,我收到了一行错误:

var sku = does_SKU_exist.ExecuteScalar();

“@SKU附近的语法不正确”任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

您忘记在where子句之后关闭),但实际上在您的情况下不需要():SqlCommand初始化应如下所示:< / p>

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

您还需要在添加参数时进行一些小改动,即:

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