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!
Related
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")
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.
According to this:
http://msdn.microsoft.com/en-us/library/ms172417.aspx, it is possible to use "DbGeography", because it will be mapped to "image" in the database side. (As when using enums, they are mapped to ints)
However,
If I have this:
public class Something
{
public long SomethingId { get; set; }
public string Name { get; set; }
public DbGeography Location { get; set; }
}
When the database is created for the first time (using EF6 with "Code First" approach), I get this exception:
There is no store type corresponding to the EDM type 'Edm.Geography(Nullable=True)' of primitive type 'Geography'.
My connection string is the following:
<add name="MyDbContext" connectionString="Data Source=|DataDirectory|MyDatabase.sdf" providerName="System.Data.SqlServerCe.4.0" />
What am I doing wrong?
I checked and my EF's dll is version 6
You cannot do this, the MSDN article Refers to the fact that the replication component move data in this column type to a "image" column in SQL Compact.
You must use:
[MaxLength]
public byte[] Location { get; set; }
to store the data, and use the Spatial libraries to convert back and forth in your app
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.
I followed the example on scottgu's blog about EF code first CTP5 but I get the error that
System.Data.SqlClient.SqlException:
Invalid object name 'dbo.Products'.
this is the code I got.
<add name="CTP5Context"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|EFCTP5.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
public class CTP5Context : DbContext
{
public DbSet<Product> Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public int Amount { get; set; }
}
var context = new CTP5Context();
var products = context.Products;
return View(products);
im kinda clueless here I done the same as the blogpost, its not my first time with EF (But CTP5 tho), I'm I overlooking something?
If your table name is Product in the database, try this:
[Table("Product", SchemaName = "dbo")]
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public int Amount { get; set; }
}
To use the Table attribute You will need to add the following using statement:
using System.ComponentModel.DataAnnotations;
Hope this helps! It worked for me.
I had the same problem but I've done 2 changes and it works for me. I changed connection string (Added initial catalog)
<add name="CTP5Context"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\northwind.mdf;User Instance=true;initial catalog=Northwind"
providerName="System.Data.SqlClient" />
and in the Global.asax I've added following line in Application_Start()
Database.SetInitializer<Northwind>(new System.Data.Entity.DropCreateDatabaseAlways<Northwind>());
The exception looks like it's coming from the database. Are you sure your table name is 'Products' or is it 'Product' (singular instead of plural?)
It seems EF Code First works differently depending on which type of database you're connecting to. If you work with SQLCE which is what ScottGu is using to showcase EF Code First, then all tables will be created with names that are not plural. However, if you use SQL Server 2008 (that's what I tested with), it expected tables names to be plural. There are few ways around this, you could add the table name attribute as Omar shows, or you could override the OnModelCreating event for the context.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
Make sure your Products table was created with the dbo Schema, a lot of times the schema will be something other than dbo, such as it can be your username or server name (if the account you're working with isnt in the db_owner schema). Open up the DB (since it's SQLExpress) with Server Explorer in Visual Studio)
To do this right click on the table name and select Open Table Definition then inside the table definition right click and select Properties and in the properties window check what is listed in the schema value. If it's not DBO then you should be able to change it to dbo and save it.