Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3309552
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T21:39:16+00:00 2026-05-17T21:39:16+00:00

I have an account table with a unique constraint on the e-mail address. My

  • 0

I have an account table with a unique constraint on the e-mail address.

My code travels through several layers Controller -> Service -> Repository -> Nhibernate

Inside the repository, an error is thrown when the unique key is violated. I want to catch this error in my service layer, so I put a try catch around it. Unfortunately, however, the error is throw up past the service layer directly to MVC.

Here’s my code samples.

First the controller:

NewAccountRequest request = new NewAccountRequest()
                {
                    EmailAddress = model.EmailAddress,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    Password = model.Password
                };

                try
                {

                    accountService.RegisterAccount(request);

                    //send the user off to recieve their activation e-mail
                    return RedirectToAction("SendActivation", new { id = model.EmailAddress });
                }
                catch (EmailAlreadyRegisteredException)
                {
                    ModelState.AddModelError("EmailAddress", String.Format("The email address {0} is already registered. <a href=\"/SignIn\">Sign In</a>", model.EmailAddress));
                }

Then, the method I am calling in the service looks like this:

    public void RegisterAccount(NewAccountRequest request)
    {
        Account account = new Account()
        {
            EmailAddress = request.EmailAddress,
            Password = request.Password
        };

        Profile profile = new Profile()
        {
            EmailAddress = request.EmailAddress,
            Name = new Profile.ProfileName() { FirstName = request.FirstName, LastName = request.LastName }
        };

        try
        {
            accountRepository.SaveWithDependence<Profile>(account, profile);
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            if (ex.Message.ToUpper().Contains("VIOLATION OF UNIQUE KEY"))
                throw new EmailAlreadyRegisteredException();
            else
                throw;
        }
        catch (Exception ex)
        {
            if (ex.Message.ToUpper().Contains("VIOLATION OF UNIQUE KEY"))
                throw new EmailAlreadyRegisteredException();
            else
                throw;
        }
    }

The nhibernate save method errors and instead of being trapped by the try-catch in the service layer, it is passed directly up to the MVC app. I have a feeling this may be due to how I set up structuremap. I have all declarations in my MVC app. Here’s how that looks:

        //repository registration
        For(typeof(MySite.Data.IRepository<>)).Singleton().Use(typeof(MySite.Infrastructure.Repository<>));

        //services
        For<MySite.Services.IEmailService>().Singleton().Use<MySite.Services.Impl.BasicEmailService>()
            .Ctor<string>("activationUrlFormat").Is(ConfigurationHelper.UrlFormats.ActivationLink)           //{0} is the email address, {1} is the HMAC
            .Ctor<string>("passwordResetUrlFormat").Is(ConfigurationHelper.UrlFormats.ResetPasswordLink);   //{0} is the email address, {1} is the HMAC
        For<MySite.Services.IAccountService>().Singleton().Use<MySite.Services.Impl.AccountService>()
            .Ctor<int>("activationLinkLifeSpan").Is(ConfigurationHelper.Defaults.ActivationLinkLifespan)         //In hours
            .Ctor<int>("passwordResetLinkLifeSpan").Is(ConfigurationHelper.Defaults.ResetPasswordLinkLifespan);     //In hours
        For<MySite.Services.IProfileService>().Singleton().Use<MySite.Services.Impl.ProfileService>();

My Service class constructor looks like this:

    IRepository<Account> accountRepository;
    IRepository<Profile> profileRepository;
    IEmailService emailService;
    int activationLinkLifeSpan;
    int passwordResetLinkLifeSpan;

    public AccountService(IRepository<Account> accountRepository, IRepository<Profile> profileRepository, IEmailService emailService,
        int activationLinkLifeSpan, int passwordResetLinkLifeSpan)
    {
        this.accountRepository = accountRepository;
        this.profileRepository = profileRepository;
        this.emailService = emailService;
        this.activationLinkLifeSpan = activationLinkLifeSpan;
        this.passwordResetLinkLifeSpan = passwordResetLinkLifeSpan;
    }

everything works, except the error try-catch. Any ideas how I configure this so the service catches the repository errors? Keep in mind that because my repository is generic, it is used in multiple services – in the code sample above it’s used in the account service and profile service.

EDIT: Adding the error message/stack trace

Violation of UNIQUE KEY constraint 'U_Email'. Cannot insert duplicate key in object 'dbo.WebAccounts'.
The statement has been terminated.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'U_Email'. Cannot insert duplicate key in object 'dbo.WebAccounts'.
The statement has been terminated.

Source Error: 


Line 81:             using (ITransaction tx = Session.BeginTransaction())
Line 82:             {
Line 83:                 Session.SaveOrUpdate(entity);
Line 84:                 Session.SaveOrUpdate(dependant);
Line 85:                 tx.Commit();

Source File: C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Infrastructure\Repository.cs    Line: 83 

Stack Trace: 


[SqlException (0x80131904): Violation of UNIQUE KEY constraint 'U_Email'. Cannot insert duplicate key in object 'dbo.WebAccounts'.
The statement has been terminated.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2030802
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5009584
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
   System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
   System.Data.SqlClient.SqlDataReader.get_MetaData() +86
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +311
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +987
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader() +12
   NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd) +278
   NHibernate.Id.InsertSelectDelegate.ExecuteAndExtract(IDbCommand insert, ISessionImplementor session) +52
   NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder) +83

[GenericADOException: could not insert: [MySite.Core.Model.Account][SQL: INSERT INTO WebAccounts (EmailAddress, IsActivated, Password) VALUES (?, ?, ?); select SCOPE_IDENTITY()]]
   NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder) +226
   NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Boolean[] notNull, SqlCommandInfo sql, Object obj, ISessionImplementor session) +204
   NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Object obj, ISessionImplementor session) +184
   NHibernate.Action.EntityIdentityInsertAction.Execute() +150
   NHibernate.Engine.ActionQueue.Execute(IExecutable executable) +117
   NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) +502
   NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) +323
   NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) +130
   NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) +27
   NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event) +63
   NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event) +89
   NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event) +191
   NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event) +260
   NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj) +256
   MySite.Infrastructure.Repository`1.SaveWithDependence(T entity, K dependant) in C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Infrastructure\Repository.cs:83
   MySite.Services.Impl.AccountService.RegisterAccount(NewAccountRequest request) in C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Services\Impl\AccountService.cs:50
   MySite.Web.Controllers.RegisterController.Index(NewUserRegistrationModel model) in C:\Users\Josh\Documents\Visual Studio 2010\Projects\MySite.Web\MySite.Web\Controllers\RegisterController.cs:66
   lambda_method(Closure , ControllerBase , Object[] ) +108
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +51
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +409
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +52
   System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +127
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
   System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
   System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
   System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
   System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +305
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
   System.Web.Mvc.Controller.ExecuteCore() +136
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T21:39:17+00:00Added an answer on May 17, 2026 at 9:39 pm

    I can’t imagine this having anything to do with StructureMap. If your dependencies are correctly resolved by the container, the container is doing its job (and you’ve got it configured correctly).

    Have you stepped through the code to ensure that (for example) you are correctly catching and re-throwing the right exception in the service?

    Set some breakpoints and see if you’re right about what is actually happening.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a table that saves some account limits like users. For most rows
I have a table like this (Oracle, 10) Account Bookdate Amount 1 20080101 100
I have a table with game scores, allowing multiple rows per account id: scores
It's common to have a table where for example the the fields are account,
I have something like this: create table account ( id int identity(1,1) primary key,
I have the following table: Table Account{ [...] email varchar(100), [...] } and a
I have a table of chalets where a chalet is referenced by an account...
I have a one-to-one relation between an Account and a User table, I'm trying
when calling a SSIS package (C# app) using LoadFromSqlServer, does the user account have
I have a hosting account with servergrid.com. I want to backup my database, they

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.