我有一组图像,我试图使用EF Core将它们添加到表(ImageGalleries)中。插入很顺利。在插入之后,我需要插入记录的id(表中有一个标识列)。我尝试了下面的帖子在StackOverflow。但是我联系不上。
获取插入行的id
public ActionResult Save(IEnumerable<IFormFile> images,RoomGalleryVM vm)
{
if (images!= null)
{
string fileName = "";
foreach (var image in images)
{
var fileContent = ContentDispositionHeaderValue.Parse(image.ContentDisposition);
fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var gallery = new RoomGallery()
{
RoomId = vm.RoomId,
Description=fileName,
Status="A"
};
Context.RoomGalleries.Add(gallery);
}
Context.SaveChanges();
//var Ids = vm.Select(c => c.Id).ToList();
}
return View("RoomGalleryIndex");
}
RoomGalleryVM
public class RoomGallery
{
public int Id { get; set; }
public int RoomId { get; set; }
public Room Room { get; set; }
[StringLength(100)] public string Description { get; set; }
[StringLength(10)] public string Status { get; set; }
}
索引页
<form method="post" asp-action="Save" asp-controller="RoomGallery">
<h6 style="margin-top: 2em;">Room:</h6>
@(Html.Kendo().DropDownList()
.Name("RoomId")
.HtmlAttributes(new { style = "width:100%" })
.OptionLabel("Select room...")
.DataTextField("RoomName")
.DataValueField("Id")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetRooms", "Reservation");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
)
<br />
<div class="demo-section">
@(Html.Kendo().Upload()
.Name("images")
.HtmlAttributes(new { aria_label = "files" })
)
<p style="padding-top: 1em; text-align: right">
<button>Submit</button>
</p>
</div>
</form>
请记住您创建的所有图库,并在保存后检索它们的Id:
var newRGs = new List<RoomGallery>();
foreach (var image in images)
{
var fileContent = ContentDispositionHeaderValue.Parse(image.ContentDisposition);
fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var gallery = new RoomGallery()
{
RoomId = vm.RoomId,
Description=fileName,
Status="A"
};
Context.RoomGalleries.Add(gallery);
newRGs.Add(gallery);
}
然后你可以得到任何你需要的id后,你已经保存(db计算的值将被打回本地对象)
var ids = newRGs.Select(rg => rg.Id).ToList();
如果你想在视图中使用它们,不要忘记将它们修补回你的视图模型中(我不清楚你想用它们做什么;这个答案的要点是:"如果你记得在保存之前向上下文添加了哪些对象,那么你可以在保存后为任何db计算值枚举它们">
把你的代码更新到下面,
public ActionResult Save(IEnumerable<IFormFile> images,RoomGalleryVM vm)
{
List<int> Ids=new List<int>();
if (images!= null)
{
string fileName = "";
foreach (var image in images)
{
var fileContent = ContentDispositionHeaderValue.Parse(image.ContentDisposition);
fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var gallery = new RoomGallery()
{
RoomId = vm.RoomId,
Description=fileName,
Status="A"
};
Context.RoomGalleries.Add(gallery);
Context.SaveChanges();
Ids.Add(gallery.Id)
}
}
var data = Ids; // here you will get list of ids
return View("RoomGalleryIndex");
}