我必须缩短下面的代码。
我需要在列中生成并保存一个唯一的引用号,如 R00001
、R00002
、R00003
等。此处为 1, 2 & 3 基于身份 key 值。
为此,我编写了两次db.SaveChanges()
。首先,我保存数据并选择已保存的数据,并通过生成该唯一 key 来更新它。是否可以生成该 key 并在保存时立即传递?
因此,我不需要在保存并更新数据后通过再次调用 db.SaveChanges() 两次来选择数据。这是我的 MVC Controller (MVC 操作)代码。
[HttpPost]
public ActionResult Create(RateTable model, HttpPostedFileBase[] files)
{
RateTable objRC = null;
if (model.RatecontractId >= 1)
{
objRC = db.RateTables.FirstOrDefault(rc => rc.RatecontractId == model.RatecontractId);
}
if (objRC == null && model.RatecontractId <= 0)
{
objRC = new RateTable();
objRC.CountryCode = model.CountryCode;
objRC.CompanyCode = model.CompanyCode;
objRC.CustomerName = model.CustomerName;
objRC.Remarks = model.Remarks;
objRC.CreatedDate = DateTime.Now;
objRC.CreatedBy = User.Identity.Name;
//Saving data into the database table.
db.RateTables.Add(objRC);
db.SaveChanges();
string uniqueRefNo = "R" + string.Format("{0:D5}", objRC.RatecontractId);
int rateContractId = objRC.RatecontractId;
//For updating the unique reference number of the contract.
RateTable result = (from rc in db.RateTables where rc.RatecontractId == rateContractId select rc).SingleOrDefault();
if (result != null)
{
result.UniqueRefNo = uniqueRefNo;
db.SaveChanges();
}
}
}
我将数据保存在 UniqueRefNo
列中,如下所示:
RatecontractId CountryCd CompanyCd UniqueRefNo
---------------------------------------------------
1 C0U001 C0M001 R00001
2 C0U001 C0M001 R00002
3 C0U001 C0M001 R00003
4 C0U001 C0M001 R00004
5 C0U001 C0M001 R00005
我想减少此代码,因为我要保存的文件也需要以 R00001.pdf
、R00002.pdf
、R00003 等格式保存.pdf
等
这是文件保存代码,并根据唯一引用号重命名文件名。
if (files != null)
{
foreach (HttpPostedFileBase file in files)
{
if (file != null)
{
//To generate the file name of the rate contract.
var fileName = "RC" + string.Format("{0:D5}", objRC.RatecontractId);
var extension = Path.GetExtension(file.FileName);
fileName = fileName + extension;
string path = string.Format("~/Documents/PDF/{0}", fileName);
if (System.IO.File.Exists(Server.MapPath(path)))
System.IO.File.Delete(Server.MapPath(path));
file.SaveAs(Server.MapPath(path));
RateTable resultForfiles = (from rc in dbTender.RateTables where
rc.RatecontractId == objRC.RatecontractId select rc).SingleOrDefault();
if (resultForfiles != null && (extension.ToLower() == "pdf" || extension.ToLower() == ".pdf"))
{
resultForfiles.PdfFilePath = fileName;
}
if (resultForfiles != null && extension.ToLower() != "pdf" && extension.ToLower() != ".pdf")
{
resultForfiles.WordExcelFilePath = fileName;
}
dbTender.SaveChanges(); //Third thime calling `SaveChanges()`
}
}
}
最佳答案
作为一个选项,您可以创建一个标识列和一个计算列,在计算列中,根据标识列计算所需的值。例如:
CREATE TABLE [dbo].[Table1](
[Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
[Name] NVARCHAR(50) NOT NULL,
[Code] AS (('R'+ REPLICATE('0',(5) - LEN(CONVERT([NVARCHAR](50),[Id])))) +
CONVERT([NVARCHAR](50),[Id]))
)
然后,当您使用 EF 或这样的查询插入表时:
INSERT INTO [dbo].[Table1]([Name]) VALUES (N'Something')
结果是:
| Id | Name | Code |
.............................................
| 1 | Something | R00001 |
重要说明
Before choosing any solution, no matter computed column, sequence, or trigger, make sure you need to store such computed code in database. I think you don't need to generate and store the reference code at database side, it's enough to use the key of the entity as a reference number / foreign key wherever a logical or physical relation is needed.
使用身份列:您可以定义身份Id
列。然后,在数据库中插入 yourEnitty
后,在 SaveChanges()
之后,yourEntity.Id
将包含新插入的标识值,您不需要对 db 的额外调用。然后您可以使用相同的 ID 作为引用(例如文件名)。
使用 Guid 列:您可以定义 Guid Id
列。然后在数据库中插入 yourEnitty
之前,将 Guid.NewId()
分配给 Id
列,然后您可以使用相同的 guid 作为引用(例如例如文件名)。
考虑以下几点:
- 存储中文件的名称或 key 以及数据库中实体的 key 是您的领土,最终用户与之无关。
- 您可能想要使用 Azure Blob、SQL 数据库、文件系统等存储,并且在任何这些存储技术中,您可以为文件使用不同的 key /名称。
- 最终用户唯一可以说的是,“我想看到具有友好名称的文件链接”,或者“我想在下载文件时有一个友好的名称”,这非常简单以便您在网格中或下载时提供这样友好的名称。
我的建议是使用 key (例如 GUID key )存储和检索文件。然后,在下载操作中,您可以轻松发送具有不同名称的文件进行下载,例如:
public ActionResult Download(Guid id)
{
var file = Server.MapPath($"~/Content/uploads/{id}.pdf";
return File(file, "application/pdf", "something.pdf");
}
关于c# - 如何根据表的最大标识键使用 Entity Framework 在 MVC 中保存数据时生成唯一编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60016398/