使用Entity Framework从控制器访问Scope_Identity

时间:2013-04-23 16:59:17

标签: entity-framework

我需要根据表格的标识生成一个值。代码正在运行,但我想知道是否有更优雅的方式来做我正在做的事情。

问题是我的控制器不知道实体框架,因此我无法直接访问EF实体,该实体将在保存上下文后保存标识值。

[HttpPost]
    public ActionResult Index(NewPlannerEntryCreateViewModel vm)
    {
        if (ModelState.IsValid)
        {
            Mapper.CreateMap<PlannerEntryRecord, TradeSpendRecord>();

                //Need to insert the records, then update them so that I
                //can leverage existing stored procs
                TradeSpendRecord r = Mapper.Map<PlannerEntryRecord, TradeSpendRecord>(vm);
                r.VersionDate = now;
                _tsRepo.Insert(r);
                _uow.Save();
                _tsRepo.PostInsert();
                _uow.Save();


            return RedirectToAction("Index", "Home", new { area = "US" });
        }

所以我调用我的repo的insert方法,它将EF实体分配给私有字段,然后在我的上下文中调用Save(),更新该EF实体,然后调用PostInsert()方法生成我的价值:

 public class TradeSpendRepository : EFRepository<tblTradeSpend>, ITradeSpendRepository
{
    tblTradeSpend _record;

    public void Insert(TradeSpendRecord record)
    {
        Mapper.CreateMap<TradeSpendRecord, tblTradeSpend>();
        _record = Mapper.Map<TradeSpendRecord, tblTradeSpend>(record);

        base.Insert(_record);
    }

    /// <summary>
    /// We need to access the identity of this record, which 
    /// we can only do after SaveChanges() is executed in the controller
    /// </summary>
    public void PostInsert()
    {
        //Build the promo id off the ID
        string promoId = (_record.ID + 1).ToString();
        promoId = "000000" + promoId;
        promoId = "P" + promoId.Substring(promoId.Length - 7, 7);
        _record.PromoID = promoId;
        Update(_record);
    }

有什么方法可以清理它吗?

克里斯

0 个答案:

没有答案