Not able to get data from local DB in diff Web Role - sql-server

I've created very simple MVC5 project with two Web roles . webRole1 with local DB which was created by code first (and generate the view by scaffold) this is working fine ,I was able to run it get view data and create data in the local DB.
Now I created very simple API in the WebRole1 to read the data from the DB which is working and I get the data via the API
I created WebRole2 and The problem is that I dont able to read the data in from this API (which is in web role1 ) in webRole2,How should I do that?I getting null for the key that I provided which is exist in DB
I can share the project in one drive if its OK.
This is the model of WebRole1
namespace WebRole1.Models
{
public class User
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string UserId { get; set; }
public string FirstName { get; set; }
}
public class ConfigModelDbContext : DbContext
{
public ConfigModelDbContext()
: base("DefaultConnection")
{
}
public DbSet<User> User { get; set; }
}
}
This is the connection string
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\User.mdf;Initial Catalog=Users;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
This is the simple API which read the data from the local DB (the data found if I call this API from webRole1
namespace WebRole1.Models
{
public class UserApi
{
private ConfigModelDbContext db = new ConfigModelDbContext();
public User getDbData()
{
User user = db.User.Find("user1");
return user;
}
}
}

Answered here by Russriguez:
Configure the second WebRole to point at the .mdf in the first WebRole (MVC project), e.g.
<connectionStrings>
<add name="Connection1" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=C:\Path\To\The\Database\Person.mdf;Initial Catalog=Persons;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
replace "C:\Path\To\The\Database\Person.mdf" with the actual full path
to the database file that is in WebRole1's App_Data directory.
Only problem is that this is an absolute path, so all developers need their repository in the same place. Not ideal, but I couldn't get relative paths to work. I tried:
..\..\..\..\..\..\[project-with-db]\App_Data\[db-name].mdf
assuming that the base directory of the second web role would be:
[src-root]\[azure-project]\csx\Debug\roles\[web-role-project-2]\approot

Related

Localdb doesn't save changes

I have a localdb that is working just fine on my development machine, however when I tried to test the app on another machine, I found that somehow changes do not take effect on the dB.
What could make entity framework behave differently on my machine than in the other one?
Here is my DbContext
public DataContext() : base("name=DBConnectionString")
{
Database.SetInitializer(new DataInitializer());
}
And the DataInitializer class:
public class DataInitializer: DropCreateDatabaseIfModelChanges<DataContext>
{
public DataInitializer()
{
}
protected override void Seed(DataContext context)
{
//Insert some seed data
Console.WriteLine("Seeding db...");
...
base.Seed(context);
}
}
and the connection string:
<connectionStrings>
<add name="DeltaDBConnectionString"
connectionString="Server=(localdb)\v11.0;Integrated Security=true;
AttachDbFileName=|DataDirectory|\DeltaDB.mdf;"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Code first migrations database error

I used this pluralsight video on MVC code first migrations to keep my default MVC IdentityDb context and create another context for custom tables. Since then I get an error trying to connect connecting to the database online:
CREATE DATABASE permission denied in database 'master'.
.........
It works locally. My connection string are correct and my context classes point to the right connection string name:
public class IdentityDb : IdentityDbContext<ApplicationUser>
{
public IdentityDb()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static IdentityDb Create()
{
return new IdentityDb();
}
}
public class CustomDb : DbContext
{
public CustomDb() : base("DefaultConnection") { }
public DbSet<Inquiry> Inquiry { get; set; }
public DbSet<Product> Product { get; set; }
}
Connection string:
<add name="DefaultConnection" connectionString="server=***.db.1and1.com; initial catalog=***;uid=***;pwd=***" providerName="System.Data.SqlClient" />
I've read that the connection string name should be the same as the context class name but since I have two contexts I need a common name (DefaultConnection) which I've specified in the contexts.
It works connecting to my local database but not when its online so I did wonder if this would relate to the migration history table being up to date online and EF 6 trying to update the database but the entries in the migrations table match.
Any help appreciated.
* UPDATE *
I tried resetting the EF migrations with this guide thinking if the migrations where out of sync with the online DB it could result in EF trying to re-create the database causing this issue. However the problem still persists!
I have now added these lines to my context constructors respectively:
Database.SetInitializer<IdentityDb>(null);
Database.SetInitializer<CustomDb>(null);
This has stopped the error but kind of defeated the purpose of EF because I now have to remove it when creating migrations and manually script the changes to the online DB, then put it back in for the site to work online.

Database doesnt work on the server but does in my development environment

I am creating a mobile web app using MVC 4, I need to use a database to store details, the site then redirects to paypal, and on its return we use the paypal token to find the details in the database, this works fine on my local system, I have changed the (localdb) to .\SQLEXPRESS and that works ok, but when I put it onto my server, I get the error message "CREATE DATABASE permission denied in database 'master'"
I have sql server running, but I just cannot get it to connect.
The code generates the db with the following code
namespace PaypalTestWebApp.Models
{
public class StudentDetail
{
[Key]
public string token { get; set; }
public string studentDetails { get; set; }
public float depositAmount { get; set; }
}
public class StudentDetailsContext : DbContext
{
public DbSet<StudentDetail> studentDetails { get; set; }
}
}
and then I construct using the following in the page before I redirect
StudentDetailsContext db = new StudentDetailsContext();
StudentDetail sdb = new StudentDetail();
if (db.studentDetails.Find(paypal.token) == null)
{
log.Info("found paypal token");
sdb.token = checkoutResponse.Token;
sdb.studentDetails = CurrentUser.UserName;
sdb.depositAmount = float.Parse(CurrentUser.DepositAmount.ToString());
db.studentDetails.Add(sdb);
db.SaveChanges();
}
and in the return page I use the following :
StudentDetailsContext db = new StudentDetailsContext();
StudentDetail sdb = new StudentDetail();
sdb = db.studentDetails.Find(token);
CurrentUser.UserName = sdb.studentDetails;
CurrentUser.DepositAmount = sdb.depositAmount;
this all works fine on my machine, and creates the database in sql, but not on the server
my connection string is as follows :
<add name="StudentDetailsContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=StudentDetails;Integrated Security=True;Trusted_Connection=True" providerName="System.Data.SqlClient" />
Any help would be greatly appreciated
Thanks

Why is Entity Framework ignoring my connection string?

I have a connection string:
<add name="Gini" providerName="System.Data.SqlClient" connectionString="user id=user;Password=pa55;Data Source=server;Database=gini" />
I want EF to be able to control the creation of the database and updates through migrations so I'm letting it have complete control over the DB.
My contact class looks like the following:
public class GiniContext : DbContext
{
public DbSet<UserSession> UserSessions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserSessionConfiguration());
}
public GiniContext() : base("Gini")
{
Database.Create();
}
}
I would expect this to create a database called "gini" on the server called "server" using the username and password as above but it's creating it on the (LocalDB)\v11.0 instance.
What am I doing wrong?
If you have two projects like a Class Library for Objects and a Web Application referencing it. You ll need to add the connection from app.config to the web.config in your web application.

What can I do to generate the DB in EF Code First?

I am not planning to use EF Code First in an MVC Website. I am looking to Utilize it in a App that has a WPF Client.
Projects are setup as
ContactManager.Core // Contains all
Entities(dll)
ContactManager.Data // Contains
the DataContext and other data
related Services(dll)
ContactManager.Services // Business
components (dll)
ContactManager.Client // WPF
Application
I am unable to generate a SQLExpress or SQLCE 4.0 DB. I am more interested in compact version db. I am not getting any error except my unit tests fail because it tries to connect a db that doesnt exist.
I found out the answer 2 Options:
Option 1:
In your DbContext you specify the connection strings in the base constructor:
public class RecetteContext : DbContext
{
public RecetteContext()
:base("<YourConnectionString HERE>")
{
}
public DbSet<Categorie> Categories { get; set; }
public DbSet<Recette> Recettes { get; set; }
}
}
Option 2:
The one I used, you give you connection string a name in the DbContext base constructor:
public RecetteContext()
: base("RecettesDatabase")
{ }
And in your App.Config file you add a ConnectionString with the same name:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="RecettesDatabase"
connectionString="Data Source=RecettesDB.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
</configuration>
Hope it solved your issue!

Resources