0
votes

I'm new to MVC and trying to add/ edit records in master detail form. Both masterid and detailid are generated by oracle on insert of record. Thus when I try to call DBContext.SaveChanges() I get error that foreign key is violated and no primary row with id '0' can be found.

Below is the class description.

public class Master
{
    public int MasterID { get; set; }
    public string MasterTitle { get; set; }
    public virtual IList<Detail> Details { get; set; }
}

public class Detail
{
    public int DetailID { get; set; }
    public int MasterID { get; set; }

    public string DetailName { get; set; }
    public virtual Master Master { get; set; }
}

Controller code

[HttpPost]
  public ActionResult Create(MASTER masterrecord)
{
   if (ModelState.IsValid)
   {
      db.MASTER.Add(masterrecord);
      db.SaveChanges();
    }
    ...
}

The primary key (masterid) will get meaningful values only after record is inserted to database. context.SaveChanges() at this point tries to save Client records too with '0' masterid. I searched every where couldn't find anything which could be of useful.

Though of saving only Master table first so that I can retrieve the masterid and us it with DETAIL model. however couldnt find anywhere how to do it using EF5 MVC ASP.NET Can any one point me to right direction of provide with some working sample? thanks Siddhant

2
working fine with sqlexpressZedBee
I'm using Oracle. The PK is generated from sequence for that I'm using Before Row Insert Trigger plus checking condition if PK COLUMN (MASTERID in my example) is = 0siddhant Kumar

2 Answers

0
votes

You might want to consider using GUIDs instead of ints for your PK. Then in your constructor for Master you can say MasterID = Guid.NewGuid();. This way you don't have to hit the database to find out what the next ID will be.

There is a pro and con list here http://www.codinghorror.com/blog/2007/03/primary-keys-ids-versus-guids.html

0
votes

If you have set a breakpoint on the Create method and are getting a proper list in your Master object, it may be an issue with the Oracle provider.

As a workaround, you could try to change the method signature to accept your data like the following:

public ActionResult Create(MASTER masterrecord, List<Detail> details)

Then you could first save the masterrecord and subsequently add your details and save again. It's not optimal, but it may work.

Side note: change your IList to an ICollection.