Why does Entity Framework automatically use the ObjectContext instead of the DbContext when mapping database tables using ADO.NET Entity datamodel - asp.net

I am following the database approach first; I have created the tables in my SQL Server 2008 database, then I map those tables to Entity Framework classes using an ADO.NET Entity Data Model. But when I opened the designer.cs file I found the following code in the class definition which was created automatically:
public partial class PortalEntities : ObjectContext
so I have the following three question that get my confused:
Why does my PortalEntities class derive from ObjectContext and not DbContext as I was expecting?
Is there a major difference between ObjectContext & DbContext, or they are mainly the same and offer that same capabilities
When I try to write the something similar to the following code:
Student student = db.Students.Find(id);
I found that I cannot use .Find() method as I used to do using DbContext, so does this mean that ObjectContext & DbContext have different methods that I can use?
BR

The DbContext is a wrapper around the ObjectContext which simplifies the interface for the things we do most.
If you have an DbContext you can still access the ObjectContexttrough ((IObjectContextAdapter)dbContext).ObjectContext;
If you want to use the DbContext instead of the ObjectContext when using database first, you can switch the template that's used for generating your code. You can do this by right-clicking in your EDMX and selecting 'Add Code Generation Item'. You can then select the DbContext template.
Here is an example of the whole process.

Since VS2012 the default code generation changed from ObjectContext to DbContext.

Related

Using code-first approach,I don't have an edmx file. what's the alternative?

I'm fairly new to asp.net mvc, so please bear with me.
I want to implement a calendar functionality, and all the tutorials I've looked at use database-first approach and have the edmx file (Entity Data Model)
I'm using code first and what can I do regarding the code that references this edmx file? do I reference context instead?
example:
public JsonResult GetEvents()
{
//Here MyDatabaseEntities is our entity datacontext (see Step 4)
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
var v = dc.Events.OrderBy(a => a.StartAt).ToList();
return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Sorry if this question is vague or not clear.
Thank you and I'd appreciate help!
In code first, you don't need an edmx file, because everything is in your own code. The basic building blocks are:
A class that inherits from DbContext. This will be equivalent to the MyDatabaseEntities class in your sample.
A set of entity classes. They basically just need to be plain classes with auto properties corresponding to your database columns. For built in conventions to work, you also need an ID, for instance an int property named Id
A set of properties on your DbContext class of type DbSet for every type T which is an entity you would like to query against. This is the Events property in your example.
In more advanced scenarios you customize the mappings beyond what the conventions can infer automatically. This can be done with attributes on your entity classes, or via a special set of APIs that can be called on your context at startup
Go to Sql server inside your database there is a folder Database Diagram, Right click New Database Diagram and explore it.

Identity 2.0: ApplicationUser extension using a database first approach

From a couple of articles I have found online
http://typecastexception.com/post/2013/10/27/Configuring-Db-Connection-and-Code-First-Migration-for-Identity-Accounts-in-ASPNET-MVC-5-and-Visual-Studio-2013.aspx
http://www.codeproject.com/Articles/790720/ASP-NET-Identity-Customizing-Users-and-Roles
I have seen it is very simple to extend the ApplicationUser class in MVC 5/Identity 2.0. It basically requires adding of property to that class and all dependent views/viewmodels etc to implement the new functionality. The only question I have remaining is due to the fact that these articles all give you examples in regards to a code first perspective. How would extending the Applicationser class work with a database first perspective?
Here is what I imagine.
1.) Change the connection string to your production database. (In my case SQL Azure)
2.) Create the tables that are normally automatically created by identity 2.0 in SQL Azure.
3.) Fill those tables with the default properties and types.
4.) Add custom properties to the AspNetUsers table. (E.G. City, Zip, etc)
5.) Add those properties to the actual ApplicationUser class
6.) Update dependent views, controllers, viewmodels etc.
Is there a more simple way in doing this?
No, there is no other way to extend ApplicationUser. Code-First is pretty much the same, only adding properties first, create migration, run migration, update your controllers/views.

Initialize database with Entity Framework 6 Code First

What is the equivalent of these lines EF5 with SimpleMembershipProvider:
if (!WebMatrix.WebData.WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
In EF6 with ASP.NET-Identity?
Those lines come from the global.asax file in the method protected void Application_Start().
The Entity Framework implementation of ASP.NET Identity uses Code First to create mappings and initialize the database. It simply uses standard EF Code First to initialize the database, so there isn't really the equivalent code that was referenced above (they're actually calls to the Simple Membership API, not EF).
When the ApplicationDbContext is first accessed (in the default MVC template, this happens in the AccountController), EF runs the context's initializer. By default, it uses the CreateDatabaseIfNotExists initializer, which checks to see if the tables are created and creates them if needed.
The Simple Membership call specifies the name of the connection string to use. In ASP.NET Identity, this is set in the constructor of ApplicationDbContext (in IdentityModels.cs).
The Simple Membership InitializeDatabaseConnection() method also takes in parameters for the table and column names. IdentityDbContext (which ApplicationDbContext inherits from) includes some default mappings to map to tables that are prefixed with "AspNet". You should be able to change them by overriding OnModelCreating() in ApplicationDbContext and supplying custom mappings.
And because it's just EF Code First, you can also create your own custom database initializer where you can supply a Seed() method that adds some initial roles and users, for example.

How to use TransactionScope while following mvc4 dependency Injection

As i am new to Dependency Injection concept. I am following Database first approach and using Entity Framework.
I have created IRepository Interface containing all crude operation.
and i have class Repository class implementing this`interface
I am creating the classes and interfaces of db tables and implementing these two into them.`How can I use Transaction scope while Insertion and Update.
And How to use joins in controller while following this pattern
If this three tables present three linked entities, you should use navigation properties in your E-F mapping. In this case, you create one entity with navigation properties and save it. Transaction will be addwd automatically.
If your entities is not linked with navigation properties, you should have in your repository special method, that will add all three entities to db and in this method you should use TransactionScope

How to get dbsets metadata from EF CodeFirst DbContext?

How do you programatically get the metadata for the dbset classes from an EF CodeFirst dbcontext? This is to loop through for code generation purposes.
After some additional research, I think I found an answer. Basically, you have to drop down into the ObjectContext, the original EF context that DbContext is a wrapper for, and use the MetadataWorkspace information below.
Please add another answer if there is a direct way to get this directly from the DbContext as it would be more intuitive and preferable if there is one.
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Data.Entity.Infrastructure;
...
using (dbcontext context = new TestContext())
{
ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
MetadataWorkspace workspace = objContext.MetadataWorkspace;
IEnumerable<EntityType> tables = workspace.GetItems<EntityType>(DataSpace.SSpace);
}
Thanks,
Will

Resources