1

Though I tried searching many post I din't get the solution. Issue in Entity Framework

Should the name of my connection string should be same as the table name provided in the DB?

Because when I gave the connection string name as the table name, I've not found any errors, but when I gave the DBContext as my connection string name,I got this exception.

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

Additional information: The connection string 'ProductContext' in the application's configuration file does not contain the required providerName attribute."

Here is my piece of code Model:

public class Product
    {
        public  int id { get; set; }
        public  string Name { get; set; }
        public int Quantity { get; set; }
        public DateTime EntryDate { get; set; }
    }

ProductContext

 public class ProductContext: System.Data.Entity.DbContext
    {
        public DbSet<Product> Products { get; set; }
        public ProductContext() : base("ProductContext") { }
    }

Controller:

public class ProductController : Controller
    {
        ProductContext db = new ProductContext();
        // GET: Product
        public ActionResult Index()
        {
            var product = db.Products.ToList();
            return View(product);
        }

web.config:

<connectionStrings>
    <add name="ProductContext" connectionString="Data Source=SHUTTHEFCUKUP;Initial Catalog=EntityFrameWork;Integrated Security=True;providerName=System.Data.EntityClient" />
  </connectionStrings>

DB table:

select * from Product
columns:
id,
name,
quantity,
date_entry

Could anyone help me out as I'm new entity framework.I'm missing something.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
Vijay Vj
  • 347
  • 3
  • 15

2 Answers2

1

Change connection string as shown below,

<connectionStrings>
    <add 
        name="ProductContext" 
        connectionString="Data Source=SHUTTHEFCUKUP;Initial Catalog=EntityFrameWork;Integrated Security=True;"
        providerName="System.Data.SqlClient" />
</connectionStrings>

providerName is an attribute in add node, it is not part of connectionString.

Akash Kava
  • 39,066
  • 20
  • 121
  • 167
0

When your connection string is named after the context it will automatically be used for that context. In this case you must have the providerName attribute set so Entity Framework knows which database connection provider to use.

You should also have a provider setup in the Web.config file with the same name for Entity Framework. This depends on the connector you're using for the database and should be documented in its documentation.

In this case it should be sufficient to add providerName="System.Data.EntityClient" into the string.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74