我有一个 C# 类 Team.cs。当我创建一个团队时,我会通过以下方式填写事件列表:
team.Events = db.Events.Where(sc => sc.SchoolcupEvent == true).ToList();
如果我只创建一个团队,它工作正常,但是当我创建第二个团队时,看起来第一个团队的事件列表又是空的,有谁知道为什么会发生这种情况?
您可以在下面找到我的 teamcreate 的代码。
团队.cs:
public class Team {
[Key]
[Required(ErrorMessage = "A name is required")]
public string TeamId { get; set; }
[DisplayName("Photo")]
public string Photo { get; set; }
[Display(Name = "Logo")]
public string Logo { get; set; }
[Required(ErrorMessage = "A sports type is required")]
public string Sport { get; set; }
public int CoachId { get; set; }
[ForeignKey("CoachId")]
public virtual Coach Coach { get; set; }
public string SchoolId { get; set; }
[ForeignKey("SchoolId")]
public virtual School School { get; set; }
public double Score { get; set; }
public List<Event> Events { get; set; }
[Required(ErrorMessage="A gender category is required")]
public string Gender { get; set; }
}
团队创建:
public ActionResult Create(Team team, IEnumerable<HttpPostedFileBase> files)
{
Coach loggedCoach = new DBUserFinder().getLoggedCoach();
team.CoachId = loggedCoach.CoachId;
team.SchoolId = loggedCoach.SchoolId;
team.Events = db.Events.Where(sc => sc.SchoolcupEvent == true).ToList();
ViewBag.Type = new SelectList(db.Sports, "SportName", "SportName");
if (ModelState.IsValid)
{
int i = 0;
foreach (HttpPostedFileBase file in files)
{
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var extention = Path.GetExtension(file.FileName);
var allowedExtensions = new[] { ".png", ".jpg", ".jpeg" };
if (allowedExtensions.Contains(extention))
{
fileName = team.TeamId.ToString();
String fullPath = "";
if (i == 0)
{
fullPath = fileName + " photo" + extention;
}
if (i == 1)
{
fullPath = fileName + " logo" + extention;
}
var path = Path.Combine(Server.MapPath("~/Content/Images/IO/Team"), fullPath);
file.SaveAs(path);
if (i == 0)
{
team.Photo = "../../Content/Images/IO/Team/" + team.TeamId + " photo" + extention;
}
if (i == 1)
{
team.Logo = "../../Content/Images/IO/Team/" + team.TeamId + " logo" + extention;
}
}
i++;
}
}
db.Teams.Add(team);
db.SaveChanges();
return RedirectToAction("Index");
}