【问题标题】:How to generate unique product Serial no based on productID and productCategoryId using LINQ?如何使用 LINQ 根据 productID 和 productCategoryId 生成唯一的产品序列号?
【发布时间】:2018-04-30 05:56:57
【问题描述】:

我正在尝试根据 productId 和 product categoryId 生成唯一的产品序列或标签?

    public string GetProductSerialNo(int productID,int categoryId)
    {

        var productSerialNo= (from a in db.AssetProductInfo
                  where a.ProductId == productID && a.CategoryId==categoryId
                  select a.ID).Max() + 1;

        return productSerialNo.ToString();
    }

如果表中至少存在一种产品,则上述代码有效。有没有更好的解决方案来使用 LINQ Query 生成产品序列号。

提前致谢

【问题讨论】:

  • 如果两个人同时运行此代码,他们将获得相同的 ID
  • 通常最好的方法是使 ID 自动递增。查一下,你会发现到处都是例子。

标签: sql-server asp.net-mvc linq


【解决方案1】:

您可以添加类别名称的前两个字符,也可以从此函数中添加唯一的编号,还可以添加毫秒的日期时间。

public string GetProductSerialNo(int productID,int categoryId,string CategoryFist2Character)
{

    var productSerialNo= (from a in db.AssetProductInfo
              where a.ProductId == productID && a.CategoryId==categoryId
              select a.ID).Max() + UniqueNumber(CategoryFist2Character);

    return productSerialNo.ToString();
}
public string UniqueNumber(string CategoryFist2Character)
{
    Random unique1 = new Random();
    string s = CategoryFist2Character;
    int unique;
    int n = 0;
    while (n < 10)
    {
        if (n % 2 == 0)
        {
            s += unique1.Next(10).ToString();

        }
        else
        {
            unique = unique1.Next(52);
            if (unique < this.characters.Length)
                s = String.Concat(s, this.characters[unique]);
        }
        Label2.Text = s.ToString();
        n++;
    }
    return s;
}

【讨论】:

  • 这并不能解决两个人同时运行的并发问题。它只是让它变得更加不可能。 保证数据库中唯一标识符的最好方法是让数据库来做。
猜你喜欢
  • 2015-02-23
  • 2015-05-03
  • 1970-01-01
  • 2020-03-10
  • 2012-11-30
  • 2021-07-13
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多