WebApi Error : An exception occurred while initializing the database

0

I have a local database .mdf file which was automatically created with MVC 5 with ASP.NET Identity. The database works in MVC 5 project but not for the WebApi project and it throws an error.

Stack Trace for Get Request:

  System.Data.DataException occurred
  HResult=0x80131501
  Message=An exception occurred while initializing the database. See the InnerException for details.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
   at System.Data.Entity.Internal.RetryAction`1.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.Initialize()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues)
   at System.Data.Entity.DbSet`1.Find(Object[] keyValues)
   at PickMeUp.Api.Controllers.PaymentTypesController.GetPaymentType(Int32 id) in C:\Users\Peeyal Khondokar\source\repos\ATP2\PickMeUp\PickMeUp.Api\Controllers\PaymentTypesController.cs:line 30
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

Inner Exception 1:
EntityException: The underlying provider failed on Open.

Inner Exception 2:
SqlException: Cannot attach the file 'C:\Users\Peeyal Khondokar\source\repos\ATP2\PickMeUp\PickMeUp.Api\App_Data\aspnet-PickMeUp-20171203014518.mdf' as database 'aspnet-PickMeUp-20171203014518'.

Connection string in all the projects is the same:

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-PickMeUp-20171203014518.mdf;Initial Catalog=aspnet-PickMeUp-20171203014518;Integrated Security=True" providerName="System.Data.SqlClient"/>

WebApi Controller :

public class PaymentTypesController : ApiController
{

    private readonly IPaymentTypeRepository _paymentTypeRepository;

    public PaymentTypesController()
    {

    }

    public PaymentTypesController(IPaymentTypeRepository paymentTypeRepository)
    {
        _paymentTypeRepository = paymentTypeRepository;
    }

    // GET: api/PaymentTypes
    public IQueryable<PaymentType> GetPaymentType()
    {
        //return db.PaymentType;

        return (IQueryable<PaymentType>) _paymentTypeRepository.GetAll();
    }

    // GET: api/PaymentTypes/5
    [ResponseType(typeof(PaymentType))]
    public IHttpActionResult GetPaymentType(int id)
    {
        //PaymentType paymentType = db.PaymentType.Find(id);
        PaymentType paymentType = _paymentTypeRepository.Get(id);
        if (paymentType == null)
        {
            return NotFound();
        }

        return Ok(paymentType);
    }

    // PUT: api/PaymentTypes/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutPaymentType(int id, PaymentType paymentType)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != paymentType.Id)
        {
            return BadRequest();
        }

        //db.Entry(paymentType).State = EntityState.Modified;

        try
        {
            _paymentTypeRepository.Update(paymentType);
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!PaymentTypeExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/PaymentTypes
    [ResponseType(typeof(PaymentType))]
    public IHttpActionResult PostPaymentType(PaymentType paymentType)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        //db.PaymentType.Add(paymentType);
        //db.SaveChanges();
        _paymentTypeRepository.Add(paymentType);

        return CreatedAtRoute("DefaultApi", new { id = paymentType.Id }, paymentType);
    }

    // DELETE: api/PaymentTypes/5
    [ResponseType(typeof(PaymentType))]
    public IHttpActionResult DeletePaymentType(int id)
    {
        //PaymentType paymentType = db.PaymentType.Find(id);
        PaymentType paymentType = _paymentTypeRepository.Get(id);
        if (paymentType == null)
        {
            return NotFound();
        }

        //db.PaymentType.Remove(paymentType);
        //db.SaveChanges();

        _paymentTypeRepository.Remove(paymentType);

        return Ok(paymentType);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _paymentTypeRepository.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool PaymentTypeExists(int id)
    {
        return _paymentTypeRepository.GetAll().Count(e => e.Id == id) > 0;
    }
}

UnityConfig :

public static class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container =
      new Lazy<IUnityContainer>(() =>
      {
          var container = new UnityContainer();
          RegisterTypes(container);
          return container;
      });

    /// <summary>
    /// Configured Unity Container.
    /// </summary>
    public static IUnityContainer Container => container.Value;
    #endregion


    public static void RegisterTypes(IUnityContainer container)
    {

        container.RegisterType<IPaymentTypeRepository, PaymentTypeRepository>();
    }
}

Projects : All the Projects in the solution

c#
asp.net-mvc
entity-framework
linq
asp.net-web-api
asked on Stack Overflow Jan 2, 2018 by Peeyalk Khondokar • edited Jan 2, 2018 by Boško Bezik

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0