开发者

How to use an Update SPROC in Entity Framework 4.1

开发者 https://www.devze.com 2023-04-11 07:01 出处:网络
Background: I originally created an application on MVC3 and Entity Framework 4.1 (Database First & Generated DBContext). I following a repository pattern. In order to meet Corp. DBA requirements,

Background: I originally created an application on MVC3 and Entity Framework 4.1 (Database First & Generated DBContext). I following a repository pattern. In order to meet Corp. DBA requirements, I need to convert all data access to using only SPROCS in order to promote the database. I'm getting stuck on a few things that I'm hoping to get answers on...

  • Insert / Delete / Update Functions

I've created my Insert, Delete, and Update Functions. I've added them to my EDM model and populated them in the 'Map Entity to Functions' tab on the Mapping details for the appropriate Entity. From what I've read, I shouldn't have the change the code in my repository class. Is this correct? (Code Below)

    public void CreateReplacementReason (ReplacementReason replacementreason)
    {
        _db.ReplacementReasons.Add(replace开发者_如何学Cmentreason);
    }

    public void UpdateReplacementReason(ReplacementReason replacementreason)
    {
        var rr = FetchReplacementReason(replacementreason.PK_ReplacementReasonId);
        rr.DF_IsActive = replacementreason.DF_IsActive;
        rr.ReplacementReasonDesc = replacementreason.ReplacementReasonDesc;
    }
  • Returning Scope_Identity()

How should a create method in my repository class look that calls a SPROC for which has a return value (Scope_Identity)? I thought I could put a return statement in my current method and change the return type. This, of course, did not work.

public int CreateReplacementReason (ReplacementReason replacementreason)
    {
        return _db.ReplacementReasons.Add(replacementreason);
    }

And this is the SPROC that is being called after being updated to return Scope_Identity()

    INSERT INTO [dbo].[ReplacementReason] ([ReplacementReasonDesc], [DF_IsActive], [CreatedDateTime])
SELECT @ReplacementReasonDesc, @DF_IsActive, @CreatedDateTime

SELECT  SCOPE_IDENTITY() AS Id

Any any all help would be appreciated.


It doesn't work because Add method doesn't save anything to the database so it cannot return the Id created in the database. The Id will be populated in your ReplacementReason directly once you call SaveChanges on your context.

So if you want method which will save record to database and return Id it must look like:

public int CreateReplacementReason (ReplacementReason replacementReason)
{
    _db.ReplacementReasons.Add(replacementReason);
    _db.SaveChanges();
    return replacementReason.Id;
}

But in most cases this is not what you want because you want to save all changes together and not execute SaveChanges after every data modification.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号