Unable to find the auto created Database - c#

I have created simple ASP.NET MVC4 application using EntityFramework Code first approach. The entity class is as below:
public class Album
{
[Key]
public int AblumId { get; set; }
public decimal Price { get; set; }
public string Title { get; set; }
}
public class MusicContext : DbContext
{
public DbSet<Album> Albums { get; set; }
}
And the web.config connection details are as below
<connectionStrings>
<add name="MusicContext" connectionString="Data Source=localhost;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
The application runs fine and I am able to add, delete, edit the album records but I am unable to find the database. When I checked the SQL server instance using SSMS there is no database created. I have not specified "Initial Catalog" value (DBName) in the web.config and not given DBname during Context creation in the code. I even checked the DB Name at run time, but it returns empty string as shown in the screen shot below. I even checked the SQL Express, no DBs created there and not even on my other instance. So where can I find the auto created DB. I am sure DB is stored somewhere because the records are stored and retrieved without any errors.

If you don't specify a database name then the connection will use the default database for the user, in this case it's integrated security so it's your Windows login. As you likely have full system admin on the server the default database will be master so you will find all your tables in there.
For a little more clarification, master is a system database and as such, to see it in SSMS you will need to navigate to Server -> Databases -> System Databases.
To fix this problem you can either:
Specify the database name in the connection string.
Change the default database for your user.
I would recommend specifying the database name though, unless you have a need to dynamically change the database for the login, then it's always better to be explicit about things like this.

Maybe it's created a local DB inside the solution. Goto View and select Server Explorer then look in the Data Connections Drop down.

Related

EF: How to use DB across multiple projects in the same solution?

I have three projects:
one containing all the models
one containing the controllers for my frontend
one containing the controllers for my customers frontend
I created a database for project (1) using entity framework (enable-migrations, add-migration, update-database).
Then I startet project (2), to create a new item and save this item in the previously created database.
However, instead of using said database, it instead created a new one (identical to the one from (1)) and saved the item there.
When starting project (3) I'm fairly sure the same thing would happen, creating a third identical database. However since (3) can't create new items, only read them, nothing happens instead.
Now that's obviously not what I want, since I need to use the items created from (2) in (3) (and ideally have them saved in the database created in (1)), so how can I achieve, that every project uses the same database?
The connectionStrings across all three projects are identical:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-db.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
The second project has a class 'Startup.Auth.cs', which the other ones don't. Since I'm not sure if it has something to with it, here's part of it:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(MyContext2.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
And here's the part of project (1) where I'm creating the context. The other projects don't have this:
public class MyContext2 : IdentityDbContext<ApplicationUser>
{
public MyContext2()
: base("DefaultConnection")
{
}
public DbSet<Items> items { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
Intellisense works fine, it automatically fills out db.items as it's suppost to, so the references are set. I'm callng the database via private MyContext2 db = new Context().
I can't get it working no matter what I try, any help is much appreciated!

How to get connection String from database and connect to it at runtime in MVC

I am new in MVC i faced a problem that i have a dropdownlist on my form with branch Name and every branch have a separate Database and user login from central Database once user login and select any of branch i want to get connection String from Database and then connect to this connection String at run time ..
Now i got the connection string from database table.i got connection string like this
name="ABCD" connectionString="Data Source=DELL27\SQLSERVER2014;Initial Catalog=TMLS;User ID=saver;Password=Abc123" providerName="System.Data.SqlClient"
The question is how to get connection to this Connection String? and get data from branch database
Option #1:
You could create an Entity Framework Entity Model for each of your databases using this getting started guide. This will make accessing different databases really easy.
// Access Abcd
using (var db = new AbcdEntities())
{
return db.Widgets.ToList();
}
// Access Efgh
using (var db = new EfghEntities())
{
return db.Widgets.ToList();
}
Option 2: Alternatively, you could use a single connection string and update the connection string at run time (see similar post). You could still use Entity Framework assuming your database schemas are all the same.

ASP.NET Identity MVC 5 working locally but throws ApplicationUser error after switch to external database

I've been following this Microsoft Article on implementing a secure web app. It is working fine with the local database. But when I change the connection string to the external database I consistently get an error when trying to interact with the identity tables
AspNetUsers
AspNetRoles
AspNetUserClaims
AspNetUserLogins
AspNetUserRoles
These tables have been re-created in the external Azure db and I followed this walkthrough. The error I get when trying to register is
The entity type ApplicationUser is not part of the model for the current context.
When trying to register it fails on this line of code in the AccountController
var user = await UserManager.FindByNameAsync(model.Email);
I want to take a database first approach as the external db already has pre-existing data. I've looked at several other posts and sites but I've been unable to solve the issue. I've also tried enabling and updating the db with no success through the Package Manager Console.
Thank you in advance!
Here is the ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
//ApplicationDbContext.Equals("", "");
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<proj.Models.Obj1> Obj3 { get; set; }
public System.Data.Entity.DbSet<proj.Models.Obj2> Obj3 { get; set; }
public System.Data.Entity.DbSet<proj.Models.Obj3> Obj3 { get; set; }
}
I don't like answering my own question but here is what resolved my problem.
I had to change the connection string from the one that was generated
<add name="DefaultConnection" connectionString="metadata=res://*/Models.DBName.csdl|res://*/Models.DBName.ssdl|res://*/Models.DBName.msl;provider=System.Data.SqlClient;provider connection string="data source=server;initial catalog=databaseName;user id=username;password=password;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
to this
<add name="DefaultConnection" connectionString="Data Source=server; Initial Catalog=databaseName; User ID=username; Password=password; Connect Timeout=60;" providerName="System.Data.SqlClient" />
I was using the connection string generated during the creation of the EDMX file, database first. Using this connection string was causing my error. I found it a bit deceiving because I was still able to access data from other tables but not the associated identity tables. I hope this will be helpful to anyone experiencing the same issue in the future.

Why is there a string ID in the data model of Azure Mobile Apps?

I'm working the C# in Azure Mobile Apps trying to learn them. I created the Model to link to my Azure SQL DB, created a DataObject like this:
public class Account : EntityData
{
//public int id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
public DateTime dtCreated { get; set; }
public Guid oGuid { get; set; }
}
Notice that I commented out the public int id above; it was giving me a duplicate column error on the query.
Finally, I created a controller using the newly created Account DataObject.
So I ran the application and hit the "tables/Account" function and it returned zero rows (but there is data and I can query it with the user I'm using in the azure mobile app).
I then noticed the model schema as this:
[
{
"id": 0,
"FirstName": "string",
"LastName": "string",
"PhoneNumber": "string",
"Password": "string",
"dtCreated": "2016-07-06T17:45:47.114Z",
"oGuid": "string",
"Id": "string",
"Version": "string",
"CreatedAt": "2016-07-06T17:45:47.114Z",
"UpdatedAt": "2016-07-06T17:45:47.114Z",
"Deleted": true
}
]
There's a couple of issues I see with the configured model (and I don't know where some of the columns are coming from...)
First, the id is listed twice, once as an int (which has to be mine) and another id as string and I have no idea where that came from.
Also, in the DB, the oGuid is of type uniqueIdentifier; not string. This may or may not be an issue because I can't test yet.
Then there are the other columns that just do not exist in my DB including CreatedAt (datetime), UpdatedAt (datetime), Version (string) and Deleted (bit).
I'm thinking the issue / reason why I'm not getting any data back from that call is that there is a data mismatch.
Do I need to add the other columns that are listed in the model in the api test?
I've also tested trying to call the /table/Account/3 to load a specific account and it returns no rows... I'm guessing it's a model mismatch but I'm not sure if that's the issue or something else causing it? I'm not seeing any errors or warnings.
Update
I figured out what is going on with model first and Azure and how to attach an existing DB in Azure to new code. I'm going to post this here for the hopes that it saves other's time. This really should have been easier to do. I'm not a fan of codefirst (yet) as I like to control the DB by hand... So this makes it a lot easier for me to work with the db backend.
First I created a new project (Azure Mobile App) then under models I right clicked the model and add->new entity data model then added in the azure db name, password and gave it my "user created profile name" as used below. This connection must be edited in the web.config as shown below.
I then had to create the model for the table in DataObjects (without the MS required columns) and create a controller off of the dataobject. I then had to edit the web.config and set a non-entity DB connection string: eg:
<add name="[user created preset name]" providerName="System.Data.SqlClient" connectionString="Server=[Azuredb server connection];initial catalog=[DBName];persist security info=True;user id=[user];password=[pass];MultipleActiveResultSets=True"/>
Finally, in the MobileServiceContext, I had to map the DataObject model to the table in Azure sql and set the connection string to use from the default MS_TableConnectionString to the connectionstring in web.config.
private const string connectionStringName = "Name=[user created preset name]";
and under OnModelCreating() I added:
modelBuilder.Entity<Account>().ToTable("tblAccount");
Where Account was the model (class) I created in DataObjects and the tblAccount is the table name in AzureDB.
The EntityData abstract class contains the additional fields - there are five fields for Mobile offline sync
Id (a string - normally a GUID - must be globally unique)
UpdatedAt (DateTimeOffset - maintained automatically via a database trigger - used for incremental sync)
CreateAt (DateTimeOffset - used as the key into the database partition to optimize reading, but unused otherwise)
Version (a byte[] - timestamp - used for optimistic concurrency / conflict resolution)
Deleted (a Boolean - used to update other clients when a record is deleted - known as soft delete).
Your client needs all these fields in its client model except for Deleted (which isn't transferred unless requested and is dealt with automatically via the Mobile Apps SDK for clearing the offline sync of deleted records).
You haven't said what languages are in use on backend or frontend. However, logging is available in both cases - you just have to turn it on, capture the exceptions, etc. Some references for you:
Node (backend): https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-node-backend-how-to-use-server-sdk/
.NET (backend): https://shellmonger.com/2016/05/11/30-days-of-zumo-v2-azure-mobile-apps-day-19-asp-net-table-controllers/

ASP.NET MVC 5 Identity with Model First

I'm developing a web application and I would like to implement Identity. I've done a couple of tests and it's pretty easy to implement when using a Code First approach.
My issue is that I can't get it to work with a Model First approach. I would like to define my models in the .edmx file, and generate my database using the "Generate database from model" option.
Here's what I've done:
I started from the default ASP .NET Web Application template, including the "Individual User Account" authentication. Then I registered a user in order for entity framework to generate the needed tables in the default database.
Then I added the "ADO .NET Entity Data Model" to my project, and chose the "EF Designer from Database" option. It has been generated successfully with the existing tables created by Identity. I changed the connection string in the IdentityModels:
public ApplicationDbContext()
: base("MyConnectionStringName", throwIfV1Schema: false)
{
}
But after this, when I try to register a user, I get the following error:
"Unable to load the specified metadata resource."
Previously, I also had an error: "The entity type ApplicationUser is not part of the model for the current context."
Is it actually possible to use Identity with a Model First approach ? If yes, what am I doing wrong ?
I said I'll post something in order to explain how I managed to get this working. I struggled to find some documentation and tutorials about using Identity with a Model First approach, so here it comes.
Firstly, I found this genius article from Ben Foster: http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1
This article discuss about how to implement an "Identity Stripped Bare". Reading it and following the steps allowed me understand how to use identity from scratch (you can see at the beggining that he generates an MVC 5 project with no authentication system).
If you want the code of this "Naked Identity", here it is: https://github.com/benfoster/NakedIdentity
The first step was to generate the database. In the Naked Identity code, the v1.0 of Identity is used. Some things are different (a couple table properties for example), but it stays mostly identical.
To create a database usable by Identity, I simply ran the template MVC 5 project, registered a user for the table to be created with the Code First approach, and then copied those tables needed by Identity in my empty database.
Once this was done, I generated my .edmx using the freshly created database. A connection string is added to the web.config. A connection string may already exist as "DefaultConnection". You need to keep this one as well.
Basically, those 2 connection strings are needed because, Identity is gonna use the default one, and the .edmx is gonna use the other one. It is not possible to use the same one for both as the .edmx connection string needs metadata, that are not supported by identity. Thus, those 2 connection strings are different, but I modified them so they can refer to the same database.
<connectionStrings>
<add name="DefaultConnectionString" connectionString="Data Source=(LocalDb)\v11.0; Initial Catalog=DatabaseName; Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="EntitiesConnectionString" connectionString="metadata=res://*/Models.WebAppModel.csdl|res://*/Models.WebAppModel.ssdl|res://*/Models.WebAppModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDb)\v11.0;initial catalog=DatabaseName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
The first connection string is the one you're gonna use with entity. So here is how the IdentityDbContext is initialized:
``
public class AppDbContext : IdentityDbContext
{
public AppDbContext() : base("QualityWebAppDbEntitiesDefault", throwIfV1Schema: false)
{
}
public static AppDbContext Create()
{
return new AppDbContext();
}
}
``
(you can find the AppUser definition in the NakedIdentity sources)
And for my .edmx, the initialization looks like this:
public partial class QualityWebAppDbEntities : DbContext
{
public QualityWebAppDbEntities()
: base("name=QualityWebAppDbEntities")
{
}
}
Hope this will help people that want to use a Model First approach with Identity.

Categories

Resources