我有这个方法:
public ActionResult Complete(int id)
{
// Validate customer owns this order
bool isValid = storeDB.Orders.Any(
o => o.OrderId == id &&
o.Username == User.Identity.Name);
bool CheckOrderValue = storeDB.Orders.Any(o => o.OrderId == id && o.Total == 0);
int musicaID = storeDB.OrderDetails.Where(o => o.OrderId == id).Select(o => o.MusicaId).FirstOrDefault();
if (isValid && CheckOrderValue)
{
int idUser = 0;
if (Request.IsAuthenticated)
{
var membership = (WebMatrix.WebData.SimpleMembershipProvider)Membership.Provider;
idUser = membership.GetUserId(User.Identity.Name);
}
var musicas = storeDB.Musicas.Where(x => x.MusicaId == musicaID)
.Select(x => new { x.Nome, x.NomeArtista, x.genero, x.path })
.ToList().First();
var y = new UsuarioMusica()
{
UserId = idUser,
MusicaId = musicaID,
GeneroId = musicas.genero.GeneroId,
genero = musicas.genero,
Nome = musicas.Nome,
NomeArtista = musicas.NomeArtista,
path = musicas.path
};
if (ModelState.IsValid)
{
storeDB.UsuarioMusicas.Add(y);
storeDB.SaveChanges();
}
return View(id);
}
else
{
return View("Error");
}
}
我想取这一行的id列表:
int musicaID = storeDB.OrderDetails.Where(o => o.OrderId == id)
.Select(o => o.MusicaId).FirstOrDefault();
在此之后,我需要将每个ID添加到数据库。
我认为我需要用列表musicaID
制作foreach
,但我不知道如何传递每个ID以添加到数据库中。
实际上,该方法只添加第一个元素,我知道为什么,是因为FirstOrDefault
方法。
如何更改此设置以添加多个ID?
您必须使用foreach循环并在添加所有元素时保存更改。例如:
public ActionResult Complete(int id)
{
// Validate customer owns this order
bool isValid = storeDB.Orders.Any(
o => o.OrderId == id &&
o.Username == User.Identity.Name);
bool CheckOrderValue = storeDB.Orders.Any(o => o.OrderId == id && o.Total == 0);
if (isValid && CheckOrderValue)
{
int idUser = 0;
if (Request.IsAuthenticated)
{
var membership = (WebMatrix.WebData.SimpleMembershipProvider)Membership.Provider;
idUser = membership.GetUserId(User.Identity.Name);
}
var musicaIDs = storeDB.OrderDetails.Where(o => o.OrderId == id).Select(o => o.MusicaId).ToList();
foreach (var musicaId in musicaIDs)
{
var musicas = storeDB.Musicas.Where(x => x.MusicaId == musicaId)
.Select(x => new { x.Nome, x.NomeArtista, x.genero, x.path }).ToList().First();
var y = new UsuarioMusica()
{
UserId = idUser,
MusicaId = musicaID,
GeneroId = musicas.genero.GeneroId,
genero = musicas.genero,
Nome = musicas.Nome,
NomeArtista = musicas.NomeArtista,
path = musicas.path
};
if (ModelState.IsValid)
{
storeDB.UsuarioMusicas.Add(y);
}
}
storeDB.SaveChanges();
return View(id);
}
else
{
return View("Error");
}
}