表自动创建记录时,另一个表得到一个新的记录
我创建了以下两类:表自动创建记录时,另一个表得到一个新的记录
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; }
}
然后我说:
modelBuilder.Entity<QuoteProduction>()
.HasKey(e => e.QuoteGeneralID);
modelBuilder.Entity<QuoteGeneral>()
.HasOptional(s => s.QuoteProduction)
.WithRequired(ad => ad.QuoteGeneral);
要设置QuoteProduction.QuoteGeneralID
领域既主键和外键。所以,现在当生成的数据库就会看起来像:
我想记录在QuoteProduction
表自动创建每当一个进入QuoteGeneral
表。这可能吗?或者,我必须自己添加吗?如果我必须自己添加它,捕获QuoteGeneralID
值的最佳方法是什么?我不认为SELECT MAX(QuoteGeneralID) FROM QuoteGeneral
将永远是可靠的,因为我可能有很多用户使用数据库,并且可能会导致错误的值。
编辑:什么工作对我来说(仅供参考,以可能帮助其他将来)
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);
}
由于QuoteGeneralID是一个外键进入QuoteGeneral表,你可以简单地创建QuoteProduction记录:
var qp = new QuoteProduction
{
QuoteGeneral = quoteGeneral
};
的quoteGeneral
对象不具有已先保存。
然后,当您保存quoteGeneral
记录时,关联的QuoteProduction
记录将同时保存。
工作就像一个魅力。 – Linger
我想在QuoteProduction表中自动创建一个记录,每当一个进入QuoteGeneral表。
Create trigger trg_test
on dbo.QuoteGeneral
after insert
as
begin
Set nocount on
insert into dbo.QuoteProduction
select requiredcolumns
from
inserted i
End
执行.SaveChanges()后,您应该能够获取该对象的ID,然后使用它来添加子表。
在你的QuoteGeneral表上使用INSERT触发器 – 2016-08-15 11:57:14
插入触发器后使用 – TheGameiswar