locked
Error showing while inserting in to table using WebApi in webform RRS feed

  • Question

  • User1839056048 posted

    Iam new to WebApi.

    I want to add records into table using webapi in a webform.

    I created a webform application.Iam using VS2013 Ultimate.I the Models folder I add class file Cutomers

      public class Customer
        {
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int CustomerID { get; set; }
            [StringLength(100)]
            public string Name { get; set; }
            [StringLength(100)]
            public string Email { get; set; }
        }

    In the Models folder add Customercontext class file

    public class CustomerContext
        {
            
            public DbSet<Customer> Customers { get; set; }
    
            internal void SaveChanges()
            {
                throw new NotImplementedException();
            }
        }

    Added connectionstring in web.config filr

    <add name="CustomerContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;" providerName="System.Data.SqlClient" />

    add Repository class file in Models folder

     public interface ICustomerRepository
        {
           
            Customer Add(Customer item);
           
        }
        public class CustomerRepository : ICustomerRepository
        {
            private readonly CustomerContext _db;
            public CustomerRepository()
            {
                _db = new CustomerContext();
            }
           
            public Customer Add(Customer customer)
            {
                _db.Customers.Add(customer);
                _db.SaveChanges();
                return customer;
            }
           
    }

    Add webapicontroller as

    public class CustomersController : ApiController
        {
            private static readonly ICustomerRepository _customers = new CustomerRepository();
            // GET api/<controller>
           
            // POST api/<controller>
            public Customer Post(Customer customer)
            {
                return _customers.Add(customer);
            }
    }

    Add following code in Global.asax file

    void Application_Start(object sender, EventArgs e)
            {
                // Code that runs on application startup
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                AuthConfig.RegisterOpenAuth();
                RouteConfig.RegisterRoutes(RouteTable.Routes);
     
                RouteTable.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = System.Web.Http.RouteParameter.Optional }
                );
            }

    when I run the program there was no errorfinally I added following code for insert

    <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script>
            $(document).ready(function(){
    
                $('#Btn_Add').click(function (e) {
                    e.preventDefault();
                    AddCustomer();
                });
                function AddCustomer() {
                    jQuery.support.cors = true;
                    var customer = {
                        Name: $('#txtName').val(),
                        Email: $('#txtEmail').val()
                    };
                    $.ajax({
                        url: 'api/Customers',
                        type: 'POST',
                        data: JSON.stringify(customer),
                        contentType: "application/json;charset=utf-8",
                        success: function (data) {
                            $('#NewCustomer').html('<li>(' + data.CustomerID + ') Name=' + data.Name + ' Email=' + data.Email + '</li>');
                        },
                        error: function (x, y, z) {
                            alert(x + '\n' + y + '\n' + z);
                        }
                    });
                }
            });
    
    
        </script>

    When i run after this there is no tbale created in App_Data folder and error was displayed in save command in repository file

    error was

    An exception of type 'System.NullReferenceException' occurred in AB_CustomerWebAPI.dll but was not handled in user code

    Additional information: Object reference not set to an instance of an object.

    How to solve this

    Regards

    Baiju

    Monday, April 3, 2017 7:02 AM

All replies

  • User527778624 posted

    Hi,

    An exception of type 'System.NullReferenceException'

    May be customer object is null, try using small case property names:

    var customer = {
                        name: $('#txtName').val(),
                        email: $('#txtEmail').val()
                    };
    Monday, April 3, 2017 9:21 AM
  • User1839056048 posted

    following is complete Error List. another problem is table is not creted

    {"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an
     object.","ExceptionType":"System.NullReferenceException","StackTrace":"   at System.Web.Http.ApiController
    .<InvokeActionWithExceptionFilters>d__1.MoveNext()\r\n--- End of stack trace from previous location where
     exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
     task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
     task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher
    .HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"}

    Tuesday, April 4, 2017 3:10 AM
  • User-2057865890 posted

    Hi klbaiju,

    In the Models folder add Customercontext class file

    public class CustomerContext
        {
            
            public DbSet<Customer> Customers { get; set; }
    
            internal void SaveChanges()
            {
                throw new NotImplementedException();
            }
        }

    The recommended way to work with context is to define a class that derives from DbContext and exposes DbSet properties that represent collections of the specified entities in the context.  If you are working with Code First, you will typically write the context yourself.

    public class CustomerContext : DbContext
    {
       public CustomerContext ()
           : base("name=CustomerContext")
       {
       }
            
       public DbSet<Customer> Customers { get; set; }
    }

    reference: http://www.entityframeworktutorial.net/EntityFramework4.3/dbcontext-vs-objectcontext.aspx

    Best Regards,

    Chris

    Thursday, April 6, 2017 7:51 AM