【发布时间】:2019-09-25 01:01:38
【问题描述】:
我是编程新手,我正在尝试上传图像并将其保存在具有当前产品 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;
}
【问题讨论】:
-
这里有一个职业提示:使用 MAX 获取下一个 id 是总是错误的,原因有几个。 ID 应该是自动递增的。插入您的记录,然后获取数据库生成的 id。