SQL Error Entity Framework Code First Approach - entity-framework

I am having troubles connecting to SQL database in code first approach. Details are as below
<connectionStrings>
<add name="MydbConn"
connectionString="Data Source=hostname\SQLEXPRESS;Initial Catalog=Test1;UserID=****;Password=****;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Below is the Context Helper
public class DBContext:DbContext
{
public DBContext():base("MydbConn")
{
Database.SetInitializer<DBContext>(new CreateDatabaseIfNotExists<DBContext>());
}
public DbSet<User> User { get; set; }
}
The User Model
public partial class UserChatLog
{
[Key]
public long UserLogId { get; set; }
public string EnterpriseId { get; set; }
}
And Finally DBHelper file
public void Save(User user)
{
DBContext context = new DBContext();
context.User.Add(User);
context.SaveChangesAsync();
}
I am getting the below exception
System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.

Assuming that your connection string is fine,
this might be the problem.
I think your base constructor is taking ("MydbConn") as database name
For specifying connection string in the base constructor i believe this is the right way base("name=MydbConn")

Related

How do I define Entity Framework provider in code?

I am using the JetEntityFrameworkProvider. I am trying to connect to an MS Access file (it has ext .sep but it is indeed an Access file).
I am trying to define the connection string and provider in code, but it is not working. Before I run I get the following error:
Unable to determine the provider name for provider factory of type 'JetEntityFrameworkProvider.JetProviderFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
I do not wish to configure the provider in the config. Surely there is a way to do this.
When I do run it (yes it will build), I get this error:
System.InvalidOperationException: 'The 'Jet OLEDB:Database' provider is not registered on the local machine.'
Context class
public class ProjectContext : DbContext
{
private DbConnection con = new JetConnection();
public ProjectContext() : base(new JetConnection(""Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\\Test-Project.sep'; Provider=Jet OLEDB:Database; Password=SEEME;""), true)
{
}
public DbSet<Component> Components { get; set; }
}
Entity class
public class Component
{
[Key]
[Column("Counter")]
public int Id { get; set; }
[Column("Name")]
public string Name { get; set; }
}
I solved this by changing the connection string to this.
public ProjectContext() : base(new JetConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Test-Project.sep'; providerName=JetEntityFrameworkProvider; Password=SEEME;"), true)
{
}
However, I have a new problem and a new error so I will post a new question.

Entity Framework, Connection String throws formatexception

I am Using Entity Framework 6.1.1
I have a class in one project, which include FBuyShopContext, another for models, and one Asp project with MVC 5
In my first project I have following
public class FBuyShopContext : DbContext
{
public FBuyShopContext()
: base("name=FBuyShopContext")
{
}
public virtual DbSet<Product> Admins { get; set; }
}
}
And a Product Model in a other Library project
public class Product
{
public Product()
{}
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
my connection string is following
<connectionStrings>
<add name="FBuyShopContext" connectionString="data source=tschikovani\SQLEXPRESS;initial catalog=OnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
and when I want to add a new product into database in my controller
FBuyShopContext db = new FBuyShopContext();
Product new = new Product ();
new.Name = "Iphone";
db.Products.Add(new);
db.SaveChanges();
I have a following exception
An exception of type 'System.ArgumentException' occurred in EntityFramework.dll
keyword not supported: 'data source'.
Why this happened? connection string is fully right
I can see three things going on here:
1) DbContext's contructor should take the name of the connection string, therefore change it to just FBuyShopContext and not name=FBuyShopContext.
public class FBuyShopContext : DbContext
{
public FbuyShopContext() : base("FBuyShopContext") {}
}
2) Your connection string ends with a ", which is an invalid character. You should remove it.
3) You should specify your primary key on the model, either using the fluent API, or by data annotations:
public class Product {
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
I'm pretty sure the error you are getting is caused by 2), but 1) and 3) would have caused you problems later.

Connection to SQL Server Management Studio with Entity Framework 6

I'm using VS 2013 and EF 6 and I want EF to create a database in SQL Server Management Studio. I'm getting this error right now:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)
With this connection string:
<connectionStrings>
<add name="BillFo"
providerName="System.Data.SqlClient"
connectionString="Data Source=SELANL293\MSSQLSERVER;Initial Catalog=BillFo;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
And this is my context class:
public class BillContext : DbContext
{
static BillContext()
{
System.Data.Entity.Database.SetInitializer<BillContext>(null);
}
public BillContext()
: base("Name=BillFo")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Bill> Bills { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<BillType> BillTypes { get; set; }
public DbSet<Attachments> Attachments { get; set; }
}
I just can't get it to work out.
//EDIT//
I tried this connection string:
<add name="BillFo"
providerName="System.Data.SqlClient"
connectionString="Data Source=SELANL293;Initial Catalog=BillFo;Integrated Security=True;MultipleActiveResultSets=True" />
and got this error instead:
Cannot open database \"BillFo\" requested by the login. The login failed.\r\nLogin failed for user 'BESAM\dangus'.
If you want to have EF create your database, you need to specify a valid initializer!
See this article Database Initialization Strategies in code-first for details - basically, you need to define what initializer should be run:
using System.Data.Entity;
static BillContext()
{
Database.SetInitializer<BillContext>(new CreateDatabaseIfNotExists<BillContext>());
}
or something else - just passing null to the .SetInitializer call tells EF to do nothing --> no database is ever going to be created!

Programmatically creating a connection string for mapping an Entity Framework Code-First model with an existing Sql Server Compact database

I've successfully mapped an Entity Framework Code-First data model with an existing Sql Server Compact database by a declarative approach using app.config but it would be great if I could build such connection programmatically with perhaps the help of the EntityConnectionStringBuilder (System.Data.EntityClient) class. Unfortunately this approach is not working as the [DbContext].Connection.ConnectionString is not accepting most of its properties.
Here's the actual working code with the faulty one commented out:
Book.cs
public class Book
{
[Key]
public string Isbn { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public DateTime Published { get; set; }
public int Pages { get; set; }
public bool InStock { get; set; }
public string Description { get; set; }
}
Catalog.cs
public class Catalog : DbContext
{
public DbSet<Book> Books { get; set; }
}
app.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add
name="Catalog"
providerName="System.Data.SqlServerCE.4.0"
connectionString="Data Source=res/Catalog.sdf"
/>
</connectionStrings>
</configuration>
Main()
static void Main()
{
// var res = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "res");
// var str = new EntityConnectionStringBuilder();
// str.Name = "Catalog";
// str.Provider = "System.Data.SqlServerCe.4.0";
// str.ProviderConnectionString = String.Format("Data Source {0}", Path.Combine(res, "Catalog.sdf"));
try
{
using (var catalog = new Catalog())
{
// catalog.Database.Connection.ConnectionString = str.ConnectionString;
// remaining code not relevant - skipped
I've tried using other builder classes such as SqlCeConnectionStringBuilder (System.Data.SqlServerCe), SqlConnectionStringBuilder (System.Data.SqlClient) and even DbConnectionStringBuilder (System.Data.Common) but apparently none of them seem to match what [DbContext].Connection.ConnectionString is expecting.
Should I conclude there is no programmatic way to achieve this?
Any advice will be surely appreciated. Thanks much in advance for your contributions.
If you are using SQL Server Compact 4.0 and DbContext with code first you cannot use EntityConnectionStringBuilder - it builds connection string for EF with EDMX file. You need SqlCeConnectionStringBuilder from System.Data.SqlServerCe assembly with version 4.0.0.0!
You should also pass the connection string to the context instance through the constructor - DbContext has constructor accepting name of the connection string (from configuration) or connection string itself.
Open a DbConnection and pass it to the DbContext constructor or use a DefaultConnectionFactory:
Database.DefaultConnectionFactory
= new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
using (var catalog = new Catalog("Catalog.sdf"))
{
}
SqlCeConnectionFactory is a ready-to-use connection factory provided by Microsoft, but you can also implement your own factory.

Entity Framework 4.1Code First connecting to Sql Server 2005

I'm trying to use the Entity Framework 4.1 RC with a SQL Server 2005 instance. I've created an empty database and I'd like to persist my POCO objects to it. My POCO looks like:
public class Cart
{
public Cart()
{
this.CartId = Guid.NewGuid();
}
public Guid CartId { get; set; }
public decimal TotalCost { get; set; }
public decimal SubTotalCost { get; set; }
public decimal Tax { get; set; }
public decimal EstimatedShippingCost { get; set; }
}
My CartContext is:
public class CartContext : DbContext
{
public DbSet<Cart> Carts { get; set; }
public DbSet<Attribute> Attributes { get; set; }
public DbSet<AttributeItem> AttributeItems { get; set; }
}
I have a connection string:
<add name="CartContext" connectionString="Server=myserver.mynetwork.net;User ID=MyUser;Pwd=mypassword;Initial Catalog=ExistingDb" providerName="System.Data.SqlClient" \>
When I try and add an object to the context and save it I get:
System.Data.Entity.Infrastructure.DbUpdateException:
An error occurred while updating the
entries. See the inner exception for
details. --->
System.Data.UpdateException: An error
occurred while updating the entries.
See the inner exception for details.
---> System.Data.SqlClient.SqlException:
Invalid object name 'dbo.Carts'.
If I profile the database I can see the user connect, look for the database in sys.tables run this query:
SELECT TOP (1)
[Extent1].[Id] AS [Id],
[Extent1].[ModelHash] AS [ModelHash]
FROM [dbo].[EdmMetadata] AS [Extent1]
ORDER BY [Extent1].[Id] DESC
Then attempt to insert my cart object. It never tries to create the Carts table. I'm guessing there's something wrong with the connection string, but I can't find examples anywhere on how to do this.
DbContext will not create table just because it doesn't exists. Once you are using existing database you must also manually create tables or create custom initializer. Default initializers are only able to drop the database and create new one with all required tables.
You can for example call:
context.Database.Delete();
context.Database.Create();
Or:
context.Database.CreateIfNotExists();
Or:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
// You don't need to call this. Initialization takes place anyway if context
// needs it but you can enforce initialization for example in the application
// startup instead of before the first database operation
context.Database.Initialize(true);