Linger Linger - 3 months ago 10
C# Question

Automatically create record in table when another table gets a new record

I have created the following two classes:

public class QuoteGeneral
{
public int QuoteGeneralID { get; set; }
public QuoteStatus Status { get; set; }

//Code and annotation removed for clarity

public int? QuoteCustomerID { get; set; }
public virtual QuoteCustomer QuoteCustomer { get; set; }

public virtual QuoteProduction QuoteProduction { get; set; }
}

public class QuoteProduction
{
public int QuoteGeneralID { get; set; }

public int testrun { get; set; }

public virtual QuoteGeneral QuoteGeneral { get; set; }
}


And then I added:

modelBuilder.Entity<QuoteProduction>()
.HasKey(e => e.QuoteGeneralID);

modelBuilder.Entity<QuoteGeneral>()
.HasOptional(s => s.QuoteProduction)
.WithRequired(ad => ad.QuoteGeneral);


To set the
QuoteProduction.QuoteGeneralID
field to be both the primary and foreign key. So, now when the database is generated it will look something like:

enter image description here

I would like a record to be automatically created in the
QuoteProduction
table whenever one is entered into the
QuoteGeneral
table. Is this possible? Or, do I have to add it myself? If I do have to add it myself, what is the best way of capturing the
QuoteGeneralID
value? I don't think
SELECT MAX(QuoteGeneralID) FROM QuoteGeneral
will always be reliable since I may have a lot of users working with the database, and it may pull the wrong value.

EDIT: What worked for me (for reference to possibly help other in the future)

public ActionResult Create([Bind(Include = "list of bind fields")] QuoteGeneral quoteGeneral)
{
if (ModelState.IsValid)
{
db.QuoteGenerals.Add(quoteGeneral);

var qp = new QuoteProduction
{
QuoteGeneralID = quoteGeneral.QuoteGeneralID
};

db.QuoteProductions.Add(qp);

db.SaveChanges();
return RedirectToAction("Index");
}
return View(quoteGeneral);
}

Answer

As the QuoteGeneralID is a foreign key into the QuoteGeneral table you can simply create the QuoteProduction record:

var qp = new QuoteProduction
{
    QuoteGeneral = quoteGeneral
};

The quoteGeneral object doesn't have to have been saved first.

Then when you save the quoteGeneral record the associated QuoteProduction record will get saved at the same time.