我創建了一個MVC 5網站來跟蹤高爾夫錦標賽的結果。我有3個關鍵表,事件有很多結果。 高爾夫球手有很多結果。所以對於的任何一行結果表我可以鏈接到高爾夫球手和事件。帶插入關係的EF插入
我首先使用EF6代碼來堅持SQL Server。
這裏是我的事件POCO:
public class Event
{
public int EventId { get; set; }
public string VenueName { get; set; }
public string CourseName { get; set; }
public String FirstTeeOff { get; set; }
public DateTime EventDate { get; set; }
public decimal Fee { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
而對於高爾夫球:
public class Golfer
{
public int GolferId { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public int CurrentHandicap { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
而對於結果:
public class Result
{
public int ResultId { get; set; }
public Golfer Golfer { get; set; }
public Event Event { get; set; }
public bool Attendance { get; set; }
public int HandicapPlayed { get; set; }
public int ScoreCarded { get; set; }
public Result()
{
Event = new Event();
Golfer = new Golfer();
}
}
這裏是我的模型方面:
public class ModelContext : IdentityDbContext<ApplicationUser>, SANDGolf.DataLayer.IModelContext
{
public ModelContext() : base("ModelContextConString") { }
public virtual DbSet<SANDGolf.DomainClasses.Golfer> Golfers { get; set; }
public virtual DbSet<SANDGolf.DomainClasses.Event> Events { get; set; }
public virtual DbSet<SANDGolf.DomainClasses.Result> Results { get; set; }
}
我正在使用以下控制器操作嘗試插入結果表以記錄出席情況。
[HttpPost]
[Authorize]
public ActionResult ExpectedAttendance(ExpectedAttendanceViewModel eaVM)
{
try
{
foreach(GolferAttendanceViewModel gaVM in eaVM.GolferAttendanceViewModel)
{
DomainClasses.Result resultDomain = new DomainClasses.Result();
resultDomain.Attendance = gaVM.Attending;
resultDomain.Event.EventId = eaVM.Event.EventId;
resultDomain.Golfer.GolferId = gaVM.Golfer.GolferId;
_context.Entry(resultDomain).State = EntityState.Modified;
_context.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
當行_context.SaveChanges();執行我得到以下錯誤:
存儲更新,插入或刪除語句影響意外數量的行(0)。自實體加載後,實體可能已被修改或刪除。刷新ObjectStateManager條目。
我是新來的EF,所以如果有人能讓我知道我哪裏出錯了,我會很感激。
爲什麼你不只是調用_context.Results.Add(resultDomain)並保存更改的任何特定原因? –