public bool ApplyMatch(TestMatch match, ApplicationUser user) { using (var db = new ApplicationDbContext()) { //获取实体对象 var contextmatch = db.TestMatches.Find(match.Id); var contextuser = db.Users.Find(user.Id); var record = new TestRecord(contextmatch, contextuser); if (contextmatch == null || contextuser == null) { return(false); } //判断是否可以继续操作 if (contextmatch.Count >= contextmatch.Limit || !contextmatch.Enabled || contextuser.Applied || !contextuser.Enabled) { return(false); } db.TestRecords.Add(record); contextuser.Applied = true; db.OperationRecords.Add(new OperationRecord(user.StudentNumber, "Apply", match.Name)); //保存,采取乐观并发 bool succeed; do { succeed = true; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { succeed = false; ex.Entries.Single().Reload(); if (contextmatch.Count >= contextmatch.Limit) { return(false); } } } while (!succeed); //检查操作成功 if (!contextmatch.RecordsCollection.Contains(record)) { return(false); } } return(true); }
public void AddHistory(ApplicationUser user) { var con = new SqlConnection(@"Server=10.1.1.68\seasqlserver;Database=ForeSea;User ID=checkin;Password=seacheckin;Trusted_Connection=false;"); var cmd = new SqlCommand("", con); object result; cmd.CommandText = @"SELECT Score FROM dbo.LST_History WHERE Id=@Id"; cmd.Parameters.Add(new SqlParameter("@Id", System.Data.SqlDbType.VarChar)); cmd.Parameters["@Id"].Value = user.StudentNumber; con.Open(); try { result = cmd.ExecuteScalar(); } finally { con.Close(); } if (result != null) { using (var db = new ApplicationDbContext()) { var contextUser = db.Users.Find(user.Id); var contextMatch = db.TestMatches.Where(t => t.Name == "Listening and Speaking Test - 1st").FirstOrDefault(); if (contextMatch == null) { db.TestMatches.Add(new TestMatch { Id = Guid.Empty, Name = "Listening and Speaking Test - 1st", Limit = 900, Visible = false, StartTime = new DateTime(2015, 12, 31, 0, 0, 0), EndTime = new DateTime(2015, 12, 31, 23, 59, 59) }); db.SaveChanges(); contextMatch = db.TestMatches.Find(Guid.Empty); } //处理数据 var record = new TestRecord(contextMatch, contextUser); record.Score = result.ToString(); if (record.Score == "2.7") { record.Score = "通过考试"; contextUser.Enabled = false; } else if (record.Score == "-1") { record.Score = "旷考"; contextUser.Enabled = false; } contextUser.RecordsCollection.Add(record); contextMatch.RecordsCollection.Add(record); db.TestRecords.Add(record); db.OperationRecords.Add(new OperationRecord(user.StudentNumber, "AddHistory", contextMatch.Name)); //保存,采取乐观并发 bool succeed; do { succeed = true; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { succeed = false; ex.Entries.Single().Reload(); } } while (!succeed); } } }