Note that there are some explanatory texts on larger screens.

plurals
  1. POEF Code First Insert Objects with One to Many gives exception."Store update, insert, or delete statement affected an unexpected number of rows (0)."
    primarykey
    data
    text
    <p>I am using POCO classes with EF Code First.</p> <p>I have a class Ball as:</p> <pre><code>public class Ball { [Key] public int BallId { get; set; } public Box Container { get; set; } [Required] public bool IsCounted{get; set;} } </code></pre> <p>and a class Box as:</p> <pre><code>public class Box { [Key] public int BoxId { get; set; } [Required] public string Description { get; set; } public ICollection&lt;Ball&gt; Balls { get; set; } } </code></pre> <p>I have a list of already created Balls, using which I wish to create a new Box! When the box is created:</p> <ol> <li>Every ball should have its IsCounted property true</li> <li>The box.Balls reference should point to the existing objects</li> <li><p>The ball.Container should point to the new Box!</p> <pre><code>public void CreateBox(string Description, ICollection&lt;Ball&gt; givenBalls) { using (var c = new BoxEntryModel()) { Box entry = new Box(); if (c.Boxes.Count().Equals(0)) entry.BoxId = 1; else entry.BoxId = c.Boxes.Max&lt;Box&gt;(b =&gt; b.BoxId) + 1; entry.Description = Description; entry.Balls = givenBalls; try { foreach (Ball ball in givenBalls) { c.Balls.Attach(ball); ball.IsCounted = true; ball.Container = entry; } c.Boxes.Add(entry); c.SaveChanges(); } } </code></pre> <p>This piece of code, gives me an exception:</p></li> </ol> <p>Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p> <p>Exception Details: System.Data.OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.</p> <p><b>Also, if i comment the line <i>c.Balls.Attach(expense);</i> the code works, but it creates new rows for each Ball that I am trying to add to the box. </b></p> <p>Please help me save the entities as per the relations. Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload