表自动创建记录时,另一个表得到一个新的记录

问题描述:

我创建了以下两类:表自动创建记录时,另一个表得到一个新的记录

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领域既主键和外键。所以,现在当生成的数据库就会看起来像:

enter image description here

我想记录在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); 
} 
+4

在你的QuoteGeneral表上使用INSERT触发器 – 2016-08-15 11:57:14

+0

插入触发器后使用 – TheGameiswar

由于QuoteGeneralID是一个外键进入QuoteGeneral表,你可以简单地创建QuoteProduction记录:

var qp = new QuoteProduction 
{ 
    QuoteGeneral = quoteGeneral 
}; 

quoteGeneral对象不具有已先保存。

然后,当您保存quoteGeneral记录时,关联的QuoteProduction记录将同时保存。

+0

工作就像一个魅力。 – 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 
+0

触发器可以在visual studio中首先使用代码创建吗?或者我将不得不手动添加触发器到数据库? – Linger

+0

+1以获得有效的解决方案。但是,如果数据库在开发阶段被删除并重新创建,我不想手动创建触发器。 – Linger

执行.SaveChanges()后,您应该能够获取该对象的ID,然后使用它来添加子表。