首页 > 解决方案 > 在 SQL 连接中存储 ID 值,如果存在则返回

问题描述

我是编程新手,我正在尝试上传图像并将其保存在具有当前产品 ID 的文件夹中。但是,当我更新图像时,会创建一个新文件夹。除了返回 maxId++,我如何将 ID 存储在 DataContext 中并返回它(如果存在)?这里是代码。

    private void upload_Click_1(object sender, EventArgs e)
    {
        OpenFileDialog opFile = new OpenFileDialog();
        opFile.Title = "Select image for this product";
        opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
        if (opFile.ShowDialog() == DialogResult.OK)
        {
        try
        {
            string iName = opFile.FileName;
            var dir = @"images/" + GetCurrentId();
            var path = Path.Combine(dir, Path.GetFileName(iName));

            if (!Directory.Exists(dir) &&(produto)this.tbprodutoBindingSource.Current == null))
            {
                Directory.CreateDirectory(dir);
            }

            File.Copy(iName, path);
        }
           catch (Exception ex)
        {
            MessageBox.Show("Unable to open file " + ex.Message);
        }
    }
    else
    {
        opFile.Dispose();
    }
        }

    private int GetCurrentId()
    {
        var result = dataContextFactory.DataContext.produtos.Max(x => x.id_produto);
        int maxId = Convert.ToInt32(result);
        if (maxId == 0) maxId = 1;
        else
            maxId++;

        return maxId;

    }

标签: c#windows

解决方案


我并没有真正得到你想要的,但我会尝试解决我遇到的问题。

  1. 您是想在每次上传新照片时创建一个新文件夹,还是要将照片重命名为[Id][FileName].jpg? 如果你想要后者,你可以改变这个
var dir = @"images/" + GetCurrentId();
var path = Path.Combine(dir, Path.GetFileName(iName));

进入这个

var dir = @"images";
var fileName = GetCurrentId() + Path.GetFileName(iName);
var path = Path.Combine(dir, fileName);
  1. 如果你想要一个自动增量 id,你应该把自动增量放在数据库上,而不是通过获取最后一个 id 并增加它。但是,如果您的 id 不是很重要(您只需要它作为唯一标识符),您可以考虑使用uuid而不是自动递增。举个例子,你可以参考这里
string id = Guid.NewGuid().ToString();
  1. File.Copy(iName, path)不需要相同的文件名 iName 和路径,您可以更改名称,不会产生任何问题。

  2. 如果产品是新记录,可以生成uuid,用于图片,再用于产品id。

string id = Guid.NewGuid().ToString();
Product newProduct = new Product();
newProduct.ProductID = id;
var dir = "@images";
var path = Path.Combine(dir, id);
File.Copy(iName, path);

如果产品是旧记录,您可以从产品中获取 id,并将该 id 用作图像名称。

Product existingProduct = getProduct();
string id = existingProduct.GetID();
var dir = "@images";
var path = Path.Combine(dir, id);
File.Copy(iName, path);

推荐阅读