2

Please help me on this.

I have written a code for getting the first record from the database using LINQ

My Homecontroler

[CustomHandleError]
    public class HomeController : Controller
    {
        Domain domain;
        public HomeController()
        {
            domain = new Domain();
        }

        public ActionResult Index()
        {
            HomePageViewModel vm = new HomePageViewModel();
            vm.Page = domain.GetHomePageInfo();

            if (vm.Page != null)
            {
                ViewBag.Title = vm.Page.PageTitle;
                ViewBag.Keywords = vm.Page.PageKeywords;
                ViewBag.Description = vm.Page.PageDesc;
                ViewBag.PageImage = vm.Page.PageTabImage;
                ViewBag.ColorCode = vm.LatestNewsLetter.IssueColorCode;
                ViewBag.emptyItemCount = emptyItemCount;
                return View(vm.Page.PageTemplate, vm);
            }
            return View(vm);
        }
}


DataAccess Method

   #region Front End
        public Page GetHomePageInfo()
        {
            try
            {
                Page pagedata = new Page();

                pagedata = context.Page.Where(x => x.PageIsHomePage == true && x.PageActive==true && x.PageVisible==true).FirstOrDefault();
                return pagedata;
            }
            catch (Exception ex)
            {
                CustomFilters.logerrortextfile.errorlog(ex, "GetHomePageInfo");
                throw ex;
            }

        }
Web config

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>

  <connectionStrings>


    <add name="dbContext" connectionString="Data Source=sqlcluster1;Initial Catalog=abc_Mvc;User ID=abc_Mvc;Password=abcd_Mvc(&amp;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation targetFramework="4.5" debug="true"/>
    <httpRuntime targetFramework="4.5" maxRequestLength="2147483647"/>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880"/>
    </authentication>
    <customErrors mode="On" defaultRedirect="~/Error/General"/>
    <!--<customErrors mode="RemoteOnly" ></customErrors>-->
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647"/>
      </requestFiltering>
    </security>
    <!--<staticContent>
      <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
    </staticContent>-->
  </system.webServer>

and it is working on local machine. when I published on the server. I am getting an error not frequently but sometimes, anyone please help me with this. I am using Entity Framework with a code-first approach.

Error Message: DataException
Exception Type: System.Data.DataException
Error Location: An exception occurred while initializing the database. See the InnerException for details.
source :EntityFramework

StackTrace:
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action
1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable
1 source, Expression`1 predicate)
at DomainLogic.Domain.GetHomePageInfo()

Inner Exception

source :EntityFramework

Inner Exception: System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Cannot open database "abc_Mvc" requested by the login. The login failed.
Login failed for user 'abc_Mvc'.
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
   at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
   at System.Data.Entity.Internal.EdmMetadataRepository.QueryForModelHash(Func`2 createContext)
   at System.Data.Entity.Internal.InternalContext.QueryForModelHash()
   at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata, DatabaseExistenceState existenceState)
   at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata, DatabaseExistenceState existenceState)
   at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
   at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
Reshmy
  • 25
  • 8
  • check your database connection string – Saineshwar Bageri - MVP Jan 09 '18 at 04:17
  • @Saineshwar: I checked, in web.config and it's correct. – Reshmy Jan 09 '18 at 04:23
  • show your connection string and remove your live values from it – Saineshwar Bageri - MVP Jan 09 '18 at 04:30
  • What does the "See the InnerException for details" reveal? Usually, that's where the really useful info is hidden .... – marc_s Jan 09 '18 at 06:03
  • System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Cannot open database "abc_Mvc" requested by the login. The login failed. Login failed for user 'abcd_Mvc'. This error is showing in the inner exception, which is not occurring frequently. I can login to the server remotely using the same password and user ID.. – Reshmy Jan 09 '18 at 07:09
  • "I can login to the server remotely using the same password and user ID" - does that mean the database is there afterwards, even if the exception occured? Or are you talking about the SQL server instance? – DevilSuichiro Jan 09 '18 at 08:52
  • @DevilSuichiro: The website is hosted on our dedicated server. sometimes am getting the login failed exception. but I can log in to the SQL server using management studio with the same UserID and Password. – Reshmy Jan 09 '18 at 09:35
  • are application and database on same server. – Saineshwar Bageri - MVP Jan 09 '18 at 09:46
  • @Saineshwar it's a clustered server – Reshmy Jan 09 '18 at 09:52
  • please update your post with the inner exception content. – tschmit007 Jan 09 '18 at 09:53
  • @tschmit007 : updated – Reshmy Jan 09 '18 at 09:59
  • I haven't found solution for this issue, Please help me on this – Reshmy Jan 11 '18 at 05:27
  • The issues have been resolved for now. our database is on the clustered server, sometimes we are losing the connection with the clustered server. so we changed the database to the hosted environment, then the error not happened. couldn't find a proper solution for this. – Reshmy Jan 17 '18 at 08:32

0 Answers0