0

FIXED

I need to read the documentation to see why it's fix the error, but adding

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

before each key that is AUTO INCREMENT fix the problem.

.

sorry about that, i read allot of questions like this I am doing, but i can't figure out what's happening...

I'm making only one request, so i'ts not concurrency ... I have 3 entitys

FIRST:

[Table("banco_bar.mesa")]
public partial class mesa
{       
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public mesa()
    {
        mesatempedido = new HashSet<mesatempedido>();
        pedidomesa = new HashSet<pedidomesa>();
    }

    [Key]
    public int idMesa { get; set; }

    [Required]
    [StringLength(100)]
    public string nomeMesa { get; set; } 


    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<mesatempedido> mesatempedido { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<pedidomesa> pedidomesa { get; set; }
}

SECOND:

[Table("banco_bar.mesatempedido")]
public partial class mesatempedido
{
    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int idMesa { get; set; }

    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int idPedidoMesa { get; set; }

    [Key]
    [Column(Order = 2)]
    [StringLength(15)]
    public string senhaPedido { get; set; }

    [Key]
    [Column(Order = 3)]
    public bool requisitadoFechamento { get; set; }

    public virtual mesa mesa { get; set; }

    public virtual pedidomesa pedidomesa { get; set; }
}

THIRD:

[Table("banco_bar.pedidomesa")]
public partial class pedidomesa
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public pedidomesa()
    {
        itenspedido = new HashSet<itenspedido>();
        mesatempedido = new HashSet<mesatempedido>();
    }

    [Key]
    public int idPedidoMesa { get; set; }

    public int? idMesa { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime dataAbertura { get; set; }

    public DateTime? dataFechamento { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<itenspedido> itenspedido { get; set; }

    public virtual mesa mesa { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<mesatempedido> mesatempedido { get; set; }
}

Doesn't matter how I try to add the SECOND or the THIRD Entity, i aways get

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

What I am doing wrong here?

var db = new Models.ModelContext();
var mesa = db.mesa.Where(m => m.idMesa == mesaId).FirstOrDefault();
if (mesa == null)
{
    return new HttpUnauthorizedResult();
}else
{
    pedidomesa pm = db.pedidomesa.Add(new pedidomesa { mesa = mesa });

    mesatempedido mtp = db.mesatempedido.Add(new mesatempedido { mesa = mesa, pedidomesa = pm, senhaPedido="bario" });

   db.SaveChanges();
   return Json(new { pm, mtp });
}

Note: If i just try

db.mesa.Add(new Mesa(){nomeMesa ="asih"}); 
db.SaveChanges();

it's persist the new entity.

Already read questions:

Does Entity Framework save related classes automatically?

Can Entity Framework add many related entities with single SaveChanges()?

How to update related entities in Entity Framework

Entity Framework Insert object with related object

and others ...

Community
  • 1
  • 1
Nicollas Braga
  • 802
  • 7
  • 27
  • 1
    with the statement db.pedimosa.add() you add both pedimosa and mesa, but mesa has a identity id (which is already there since it is retrieved from database). This does mean EF will add both objects, resulting in mesa to get a new id, however the old mesa is still there (and the id is saved in the object!). So EF will look for mesa with the old id, notice it has not been altered, and throw this exception. You have to ONLY set the FK and remove the navigation property, or set the state of mesa to Modified or Unchanged. – DevilSuichiro Oct 06 '16 at 07:05
  • I'll give a try about it when i get home, but let me see if i understood, the _navigation property_'s are **virtual ICollection** alright ? So the problem is the way that the _EF_ wizard translated my _DataBase_ to _CodeFirst_ ? Soo if i need to sync the **CF** with the **DB** I'll need to remove again the _navigation's property_? And a **workaround** for it is to set states of entity'es as **Modified or Unchanged** ? – Nicollas Braga Oct 06 '16 at 11:00
  • they can be virtual, this only effects lazy loading though. no, the problem is how the .Add function behaves. it will attach all entries in the object tree to the context in added state. The navigation property does not effect the way the model is mapped to the database, however all entries in the navigation properties are attached as well, which is your problem since you actually only want to attach parts of your object tree. when the navigation property is null, obviously the related entry is not attached again and your problem is fixed (this also means FK constraints are not checked!) – DevilSuichiro Oct 06 '16 at 12:15
  • the workaround, or rather, I believe, the best fix would be to tell EF you want the navigation property to be considered, but it should not be added but rather modified (if FK's are to be modified within it) by setting the entity's state of the entry already in the database to modified. – DevilSuichiro Oct 06 '16 at 12:17
  • Unfortunately set mesa to Modified or Unchanged doesn't fix – Nicollas Braga Oct 07 '16 at 01:02
  • I saw that if i manually add the pedidomesa ID (_that is Auto Increment_) its being persisted – Nicollas Braga Oct 07 '16 at 01:33

0 Answers0