c# - 在 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;
}
解决方案
我并没有真正得到你想要的,但我会尝试解决我遇到的问题。
- 您是想在每次上传新照片时创建一个新文件夹,还是要将照片重命名为
[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);
- 如果你想要一个自动增量 id,你应该把自动增量放在数据库上,而不是通过获取最后一个 id 并增加它。但是,如果您的 id 不是很重要(您只需要它作为唯一标识符),您可以考虑使用uuid而不是自动递增。举个例子,你可以参考这里。
string id = Guid.NewGuid().ToString();
File.Copy(iName, path)
不需要相同的文件名 iName 和路径,您可以更改名称,不会产生任何问题。如果产品是新记录,可以生成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);
推荐阅读
- wpf - 应用控件模板后 WPF XAML 文本框不可编辑
- python - Python - 重新分配具有最低可能值的优先级列表
- jitsi-meet - 如何理解 Jitsi 的源代码以根据需要修改或添加一些功能
- sql - 如何根据表数据返回标志值
- google-cloud-dataflow - 是否可以直接覆盖在构建时设置的 Dataflow 模板参数?
- javascript - 如何在 AGGRID 中清除过滤器时获取列名?
- sql - SQL Postgres 显示边缘的详细信息
- laravel - 从选定的组中挑选一张图片并将其存储在数据库中 - Laravel
- scala - PySpark 中的 SparkSession 和 SparkContext 启动
- amazon-web-services - 具有相同自定义域、不同路径映射的多个 SAM 模板