Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
SQL
CREATE TABLE [dbo].[Deduction_1](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Ded] [numeric](18, 0) NOT NULL,
 CONSTRAINT [PK_Deduction_1] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


DBContext
C#
using System;
using System.Web;
using System.Data.Entity;

namespace ASPNETMVCApplication.Models
{
    public class BookDBContext:DbContext
    {
        
        public DbSet<book1> Deduction_1 { get; set; }
    }
}


Model Class
C#
using System;
using System.Web;

namespace ASPNETMVCApplication.Models
{
    public class Book1
    {
        public Int64 Id { get; set; }
        public Decimal Ded { get; set; }
        

    }
}


Controller
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ASPNETMVCApplication.Models;

namespace ASPNETMVCApplication.Controllers
{
    public class DeductionController : Controller
    {
        BookDBContext _db = new BookDBContext();

        //
        // GET: /Deduction/

        public ActionResult Index()
        {
            var deductions = from deduction in _db.Deduction_1
                             select deduction;

            return View(deductions.ToList());
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {

            Book1 deduction = new Book1();
            if (ModelState.IsValid)
            {
                deduction.Ded = Convert.ToDecimal(collection["Ded"].ToString());


                _db.Deduction_1.Add(deduction);
                _db.SaveChanges();

                return RedirectToAction("Index");
            }
            else
            {
                return View(deduction);
            }

        }
    }
}


I got this Error
System.Data.SqlClient.SqlException: Invalid object name 'dbo.Book1'. Near the <pre lang="cs">_db.SaveChanges();
Posted
v2

1 solution

Please Put the attribute above the entity like this.
C#
[Table("Tablename")]

Please make sure the tablename is the name of the table that we need to insert.
C#
<pre lang="xml"><pre lang="c#">[Table("Tablename")]</pre>
<pre lang="sql">public class Book1
   {
       public Int64 Id { get; set; }
       public Decimal Ded { get; set; }


   }</pre>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900