by default where the data is stored in mvc 3 - asp.net-mvc

simply i take mvc 3 project then add model "class1" in that there is another class "person"
in class1 there is two properties id,name and
in class person i inherits dbcontext class and it contains
"public DbSet classes { get; set; }"
and i take default1controller with read/write actions and views, using entity framework and
set
model class "class1" and
data context class "person"
so now my program runs successfully
and i can insert the data but i don't know that where it stores the data.
plz help me.

It might use SQL Server Compact which stores data in a file inside the ~/App_Data folder.

I've not yet used MVC 3 but have a look at your Visual Studio solution. See if there is an App_data folder and expand that. In there you might see an MDF database. Chances are the data is stored in there.

The only thing that I would add to #ManishG's comment:
it stores the data in my local sqlexpress
is that, for connecting to a sqlexpress instance, you should put (local)\SQLEXPRESS in the Server Name field if you are creating a connection from VS 2010 Server Explorer.

Related

How can I create and use views using EF6 Code First?

Is there actually any official strategy for creating and using views with EF6.1 Code First? I can reverse the database into Code First and get tables not views. I can import the database into Model First and get views and then do Generate DB from Model and my edmx is modified and the views are converted to tables. MSFT seems to have all but abandoned Model First, and the new Update 2 seems to have reverse engineering for Code First so I feel forced to convert to Code First but has the EF team given support for any reasonable approach to using views or stored Procedures in Code First? After all CF is supposed to create the DB but what - are you no longer supposed to use either of these SQL Server features in a .NET EF application?
For starters you can use views and stored procedures that are already created in the database. For views you don't have to do any mapping if you create a code like this:
public TestContext : DbContext
{
public DbSet<User> AdminUsers { get; set; }
}
And you have a view in the database named dbo.AdminUsers and it can be mapped to the class User (contains all required properties with the same name as the property).
For stored procedures you can use the SqlQuery function either through the Database property of the DbContext such as:
var userActivityReport = context.Database.SqlQuery<UserActivityReport>(
"dbo.GetUserActivityReport #p0, #p1", startDate, endDate);
Or through the SqlQuery function of the DbSet class:
var newUsers = context.Users.SqlQuery("dbo.GetNewUsers #p0", count);
If you want to create, modify or delete views and stored procedures via Entity Framework you can either use custom migration operations see http://dolinkamark.wordpress.com/2014/05/03/creating-a-custom-migration-operation-in-entity-framework/
For event better integration you can use the Public mapping API with a library provided by a community member: https://codefirstfunctions.codeplex.com/

how to manage two EDMX files incase they have the same table name

I am working on an asp.net mvc web application,. i use the entity framework ADO.net entity data module to map two different databases and i have created two EDMX files. but unfortunately these databases have two tables with the same name UserGroup & Router. so i am unable to map these two tables inside the EDMX files, as entity framework will automatically delete the existing table which have the same name.
can any one advice how i can fix this , without having to rename the tables ?
You may change the name of the table on designer. Click the entity on designer and click and change the name property. Or you may have these two edmx in different name spaces (If it is possible)
Each EDMX file will have some namespace :
using DB1DBModel;
using DB2DBModel;
Class MyClass
{
void SomeMethod()
{
// table with same name MyTable in first edmx
DB1DBModel.EntitiesXYZ.MyTable=new DB1DBModel.EntitiesXYZ.MyTable();
// tables with same name MyTable in second edmx
DB2DBMode2.EntitiesABC.MyTable=new DB2DBMode2.EntitiesABC.MyTable();
}
}
// Hope this works

Questions about model first MVC 3 using Entity Framework

I was playing around with Entity based on this article in Visula Studio Express 2012: http://msdn.microsoft.com/en-us/data/gg685494.aspx
Had to completely re do this after some findings:
According to the article you can create database, this is correct but classes are not created unless you right click on an empty part in the diagram choose properties and select something for "code generating strategies" (I only had default). After that my project didn't build anymore because of errors. Trying to do it again an a newly created project didn't crate the model classes anymore (not sure what I did to make it work the first time).
After creating products in the diagram, create a database and then use that database in a second project to create models the products.cs file is created but without annotations (I had product name as 200 char max but it's not in the products.cs file).
After scaffolding controllers and views in the second project (making models from database created from models in the first project) the product name is incorrectly validated to 200 char max. Even though the designer shows 200 max the products.cs file is missing annotation.
If I am doing something wrong here could anyone explain to me how to create product.cs file from an Entity diagram and still be left with a buildable project?
Is it normal for model classes created from database to have no annotation (for example max 200 char field)?
I like Entity and the idea of it. Lots of documentation out there with videos but for now I'll go out and buy a hat because will pull all my hair out trying to get used to way it works :-)
It's cool to create database with entity classes using the designer but creating the classes from the designer or from the database is not (yet) working properly.
No annotations so no checks for null or anything. I manually created the classes and added annotation for product name:
public int Id { get; set; }
[DisplayName("Product name"),
Required(ErrorMessage = "Product Name is required"),
StringLength(10)]
public string Name { get; set; }
Then right click controllers folder in solution explorer and choose => add => controller => using entity framework as a template to create crud views.
For some reason here I have to create a data context class that creates yet another connection string and database.mdf file but ... form validation works perfectly in JavaScript and on server.

How to autoCreateTables along with SimpleMembership tables in ASP.NET MVC

Today, I created a new ASP.NET MVC 4 project - Internet application.
With all the files that comes in the solution in the Account Controller I saw an attribute called [InitializeSimpleMembership]
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{}
and by only providing a proper db connectionstring property in the web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;
Initial Catalog=demo;
User ID=test;Password=test;" providerName="System.Data.SqlClient" />
and when the application runs, it checks if the available database exists or not and if not creates one and adds few memebership tables to it also. I must say I was very very impressed with the new MVC 4 - Internet app template.
Which brings me to my question :
I liked the idea of creating database and executing script from the application. I wanted to know how to add more tables to this.
For example : In the InitializeSimpleMembershipAttribute.cs file it check if a database is present, if not it creates it using the credentials present in the web.config and also adds the following tables to it.
UserProfile
webpages_Membership
webpages_OAuthMembership
webpages_Roles
webpages_UsersInRoles
what changes do I have to make to have my other tables to be added along with this ?
If this is possible, the idea of keeping sql scripts and executing them on each clean deploy can be avoided. I am working on a self-host MVC app ( It's Open-source, soon to come on Codeplex ;) ) so this will really be good for people who want to use my app without getting their hands dirty in SQL scripts.
Please can some one let me know if this is even possible. Thanks
There are two distinct parts to the tables being created:
The UserProfile table is created by adding the attribute [Table("UserProfile")] before the model in Models/AccountModels.cs (remember to add it as a DbSet to your context as well).
The 'webpages_' tables are created by the WebSecurity.InitializeDatabaseConnection call in Filters/InitializeSimpleMembershipAttribute.cs called by adding the [InitializeSimpleMembership] in Controllers/AccountController.cs. These are 'internal' tables required by the SimpleMembershipProvider and you would not typically want to alter them.
This is called the CodeFirst method of the EntityFramework (your other options are ModelFirst and DbFirst). To have your own POCOs/models auto created you would want to add the Table("TableName") attribute similar to UserProfile above.
Refer to the Entity Framework Website for full walkthroughs of the CodeFirst approach (and much much more).
http://msdn.microsoft.com/en-us/data/ef.aspx

Asp mvc 3 noobie: Why is the code-first method not building my DB on sql server?

I am an ASP MVC 3 noobie who has done a few tutorials. Now I'm trying to build a site. All of the tutorials on the microsoft website emphasize the code-first approach: you define your model with code and then create a datacontext and then the entity framework creates/manages the DB based on your code.
I set up an Employees class and a DataBaseContext class that inherits from DbContext. I added a connection string to Web.config connection string that successfully links DataBaseContext to an already existing empty DB on SQL server. EDIT= That was the problem. See my answer below
But when I try to run the Employees controller created thru scaffolding, I get this error
Invalid object name 'dbo.Employees'.
Description: An unhandled exception occurred during the execution of...
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Employees'.
I followed this post SqlException (0x80131904): Invalid object name 'dbo.Categories' and realized that if I create an employees table on the DB, this excpetion goes away (I get a new one saying that the column names are invalid).
But I thought the whole point of MVC 3 is that the framework will make the DB for you based on the code.
Maybe I need a line of code in the Global.asax Application_start() to create the database? Here is my application_start method:
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterGlobalFilters(GlobalFilters.Filters)
RegisterRoutes(RouteTable.Routes)
End Sub
Here is the code for Employee:
Public Class Employee
Property EmployeeID As Integer
Property First As String
Property Last As String
Property StartDate As DateTime
Property VacationHours As Integer
Property DateOfBirth As DateTime 'in case two employees have the same name
End Class
Here is the code for the DB context:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
What am I missing?
By default EF uses DropCreateDatabaseIfModelChanges<TContext> database initializer. Accordingly to the MSDN:
An implementation of IDatabaseInitializer<TContext> that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created. This is achieved by writing a hash of the store model to the database when it is created and then comparing that hash with one generated from the current model.
Since the database was created manually, EF can't find the hash and decides do not perform any further initialization logic.
You might want to look into this article, same question successfully answered already.
Or it can be this (also resolved successfully)
Answer to your problem is most likely one of the two.
Hope this will help you
Does the name you're specifying for your connection string match the name of your database context?
For example:
Context
var myDbContext = new MyDbContext();
Connection string
<connectionStrings>
<add name="MyDbContext" connectionString="YOUR.CONNECTION.STRING" providerName="System.Data.SqlServer" />
</connectionStrings>
Try and see if this post I wrote about DbContext with MVC works for you: Code-First
Not a lot to be done to get this to work, but there are a few things that are easily missed that will cause a bunch of head aches.
hope this helps
I had already created a database with that name on SQL server. Once I deleted the existing database, the code first framework created the tables for me like it was supposed to. It seems like if the database already exists, the framework won't set up the tables for you. It wants to create the whole DB from scratch.
You were using AdventureWorks Database?
It has it's own schema assigned to the employees table. HumanResources.Employees and not the default dbo.Employees.
Even though I've identified the problem, I don't know the solution to using the database as configured with the HumanResources schema.
Anybody know?

Resources