Linger Linger - 1 year ago 56
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:

.HasKey(e => e.QuoteGeneralID);

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

To set the
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
table whenever one is entered into the
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
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)

var qp = new QuoteProduction
QuoteGeneralID = quoteGeneral.QuoteGeneralID


return RedirectToAction("Index");
return View(quoteGeneral);

Answer Source

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.