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

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

Related

Strange schema naming with EF core code-first

I'm having a weird issue that I've never seen before, with schema naming using EF core code-first.
I just created a new class LogEntry used to log SMS and emails sent to our users.
public class LogEntry
{
public LogEntry(Guid id)
{
Id = id;
}
public Guid Id { get; set; }
public Provider Provider { get; set; } // Enum
public string Content { get; set; }
public string Recipient { get; set; }
...
}
I then added configuration in my database context class, in OnModelCreating(modelBuilder modelBuilder)
public virtual DbSet<LogEntry> Log { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LogEntry>(entity =>
{
entity.HasKey(log => log.Id);
entity.HasIndex(log => log.Date);
entity.HasIndex(log => log.Provider);
entity.HasIndex(log => log.Recipient);
...
});
}
Then I ran dotnet ef migrations add SomeMigration to actually add the migration. I setup auto migration so it automatically updates my database when the project launches. So far so good.
Now, once I went to check out the new tables it created, I made a weird naming convention regarding the databae schema.
My IIS website application pool is running with a specific managed AD user, let's call it msvc-log-api
I'm used to EF always using the dbo schema, as it default to that schema, but for some weird reason, EF decided to create a new schema named after my managed AD user mydomain\msvc-log-api$. This means that my tables are named in the following way:
mydomain\msvc-log-api$.__EFMigrationHistory
mydomain\msvc-log-api$.Log
Any idea why this is happening, and do I really need to add modelBuilder.HasDefaultSchema("dbo") to mitigate this issue?

code first .net core publish has no database tables

I'm pretty new to both Azure and code first. I have an app which works locally. I published the web project using the visual studio wizard. All worked well.
However its missing all the db tables.
I had a look at the connection string which has a "DefaultConnection". Locally its "Server=(localdb)\...".
In azure it appears as "Data Source=tcp:Sniipedb.database.windows.net,1433"
I have a db initializer which seeds the data but it only works locally.
My AppDBContext I assume should have created the db.
The actual error on the site online is "SqlException: Invalid object name 'Users'.
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)"
When I look in the DB, however, there are no tables.
I'm making a simple chores app. Users is a DB table.
To create users I have the following:
within startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<ITaskRepository, TaskRepository>();
services.AddMvc();
}
within the AppDBContext : DbContext
public DbSet<User> Users {Get; set;}
User is a simple class
public class User
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Key]
public string EMailAddress { get; set; }
public ICollection<UserTask> UserTasks { get; set; }
}
I have a DBInitializer which seeds new users and saves the context.
This works flawlessly on the local machine.
The solution for me was to configure my Publish. Within the settings it has a "databases" option where the "use this connection string at runtime" was unchecked.
Also under "Entity Framework Migrations" the "Apply this migration on publish" was unchecked.
By checking those two, then saving and then publishing it worked.

net core 1 (dnx 4.5.1) with enterpriselibrary 6 - setting up the connection string

i ve big problems running enterprise library data access block with net core 1 (dnx 4.5.1)
How can i setup the default connection string for entlib
my appsettings.json
"ConnectionString": "Server=localhost\sqlexpress;Initial Catalog=blind;User Id=blind;Password=blind"
Here is my problem (no default connectionstring)
Database db = DatabaseFactory.CreateDatabase();
how can i pass the appsettings ConnectionString to the entlib databasefactory
any help would be greatly appreciated
I know it's an old question, but I have a similar setup (but using .NET Core 2.0) and it took me awhile to figure out how to set the default database connection without using the web.config to manage it.
What I did was include the default database and all of the connection strings in the appsettings.json and then in my Startup class I read the appsettings.json into an object that I defined to store the default db name and the connection strings and configure the default + named database using DatabaseFactory.SetDatabase.
DatabaseFactory.SetDatabases() Definition
public class DataConfiguration
{
public string DefaultDatabase { get; set; }
public List<ConnectionStringSettings> ConnectionStrings { get; set; }
}
public class Startup
{
public Startup(IConfiguration configuration)
{
//Get the Database Connections from appsettings.json
DataConfig = configuration.Get<DataConfiguration>();
var defaultDb = DataConfig.ConnectionStrings?.Find(c => c.Name == DataConfig.DefaultDatabase);
DatabaseFactory.SetDatabases(() => new SqlDatabase(defaultDb.ConnectionString), GetDatabase);
Configuration = configuration;
}
public Database GetDatabase(string name)
{
var dbInfo = DataConfig.ConnectionStrings.Find(c => c.Name == name);
if (dbInfo.ProviderName == "System.Data.SqlClient")
{
return new SqlDatabase(dbInfo.ConnectionString);
}
return new MySqlDatabase(dbInfo.ConnectionString);
}
}
Whenever there is documentation, I always suggest reading it as it is usually good. This is one of those examples, check out the "Getting Started with ASP.NET 5 and Entity Framework 6". There are several things that you need to do to ensure that you are correctly configured.
Setup your connection string and DI.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
}
Also, notice the path in the configuration, it seems to differ from yours.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped((_) =>
new ApplicationDbContext(
Configuration["Data:DefaultConnection:ConnectionString"]));
// Configure remaining services
}

Network-related error for sql connection

I am trying to create a simple database using entity framework code first but when I run my project I get exception on line where i am retrieving list from database:
Exception:
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.
Code:
public ActionResult Index()
{
using(var db=new OdeToFooddb())
{
var model = (from r in db.Restaurants select r).ToList();
return View(model);
}
}
Model:
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<RestaurantReview> Reviews { get; set; }
}

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

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

Resources