开发者

Need to call stored procedures inside an entity

I have this public operation in my service:

    void IApplicationService.DeleteApplication(int id)
    {
        var repository = UnitOfWork.CreateRepository<Application>();

        var application = repository.GetByKey(id);
        OnCommit.Run(() => DeleteInvitations(id)); // ouch!!
        repository.Delete(application);
    }

OnCommit.Run() schedules an 开发者_开发问答action to run when I called SaveChanges(), implemented in a WCF inspector. DeleteInvitations has access to an object context and invokes a stored procedure to delete every item in collection application.Invitations. I made this way to avoid loading all invitations in memory only to delete them in the next step. My Repository.Delete() in turn calls Delete() in the entity.

But I don't quite like having part of the delete being handled by service code. I need to have access to stored procedures inside my entities.

I think I could make an IStoredProcedures interface and provide it to each entity. Then I could have something like this:

    public void Delete()
    {
        Contract.Requires(EntityState == System.Data.EntityState.Unchanged);

        if (Responses.Any())
            throw new ValidationException("There are responses.");

        // *..* relationship, just break that
        for (int i = Forms.Count - 1; i >= 0; i--)
        {
            var form = Forms.ElementAt(i);
            Forms.Remove(form);
        }

        // I could have something like this, perhaps?
        StoredProcedures.Call("DeleteInvitations", this.Id);
    }

What do you feel about it? Any suggestions?

Some requirements I've put:

  • Service code shall call only repository and entity methods
  • Repository shall be generic
  • Entities shall not have access to object context


I don't see problem, can you please explain what you want to do.

You can add stored procedures to your entity model, and call it like any other method or/and you can call procedure like this:

string sp = "Entities.StoredProcedureName";
var conn = (EntityConnection)dbContext.Connection;
conn.Open();
EntityCommand cmd = new EntityCommand(sp, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("Parameter1", [type]).Value = paramvalue;
cmd.ExecuteNonQuery();

You can make this execution generic if you want and dynamically pass stored procedure name and parameters.

I hope i understand what you want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜