Eager Loading with Entity Framework and Asp .net mvc (From a rails background) - ruby-on-rails

I have a few tables that reference the same table. For example:
Person has an address.
Business has an address.
When using the models I would like to do this in the controller:
person.Address.Zip
business.Address.Zip
I'm coming from a rails background where I can just declare a relationship and have all the above functionality. Force loading of the address when I get the object (person or business).
I'm new to entity framework, and I'm struggling with how to achieve that functionality. I can't include the table in both models (person and business). If I use repository pattern and add the objects to a partial for the class, then I'm using lazy loading.
Am I looking at this wrong? Any suggestions for patterns I could use?

If your using Entity Framework 4.0 with Visual Studio 2010 lazy loading is automatic.
If your using Entity Framework 1.0 your life just got harder...
To eager load with EF1 you have to use the Include() method on your ObjectQuery and specify which navigation properties ( address ). For example:
ModelContainer.Persons.Where(#p => #p.Id == 39 ).Include("Address")
For "lazy" loading you have to manually load all of the FK associations manually. For example:
var myPeople = ModelContainer.Persons.Where(#p => #p.Id == 39
if( !myPeople.Address.IsLoaded() )
myPeople.Address.Load()
Another option is to modify how EF1 generates your model types and include lazy loading out of gates.
http://code.msdn.microsoft.com/EFLazyLoading

Previously, I was creating an ADO.NET Entity Data Model for each controller.
Now I've created one Data Model for all tables (it's not a monstrous db). That way I can include the tables when I query for eager loading.
If anyone has a better suggestion. Let me know. If anyone knows the correct behavior with a large database, please comment. Would you want one large edmx file to represent the database?

Ideally you should be able to traverse the object model to get most of the data you need, starting with a reference to the current user object.

Related

Entity Framework Overhead

I am building an application that will interface with my database backend using EF 6. I have my database built so I will be going the database first approach.
One of the goals will be to utilize the grid control from DevExpress and allow the user to view a Master/Detail style of information for each Facility in my Facility table.
I need the ability to update/insert so I would assume using a view would not be as good as actually supplying the context to the grid's data source.
My question is trying to understand the overhead involved with Entity Framework. If my table contains 20 columns but my Grid only needs 10 of these for viewing/updating/inserting does the application still load ALL of the information into memory? Am I better off using a view for the grid and some form of custom routines for an update?
It doesn't necessarily load all of the columns. If you're smart about it, you can only have it load those columns that you need using LINQ to Entities.
For example:
var records = db.MyTable.Where(...Some condition...).ToList(); will return all the columns.
But doing it this way
`var records = db.MyTable.Where(...Some condition...).Select(x => new MyModel { ...some fields here... }
will only load those fields that are specified.
I've worked with DevExpress and Entity Framework combined before, and I can tell you that it's relatively painless as long as you understand what you're doing with Entity Framework, and don't just blindly have your grids make queries that can get expensive.

EntityFramework database vs model

I understand the fact that generating a model based on the DataBaseFirst method woill produce a collection of entitites on the ORM that are essentially mapped to the DB tables.
It is my understanding, that if you need properties from other entities or just dropdownlist fields, you can make a ViewModel and use that class as your model.
I have an AppDev course that I just finished and the author wrote something that if I understand it correctly, he is referring to change the ORM entities to fit what your ViewModels would look like, hence, no need for ViewModels. However, if you do this, and regenerate the ORM from the database, those new entities that you placed as "ViewModels" would be gone. If you changed the ORM to update the database, then your database structure in SQL Server would be "undone".
Please inform me if my understanding is correct that I simply need to use a ViewModel in a separate folder to gather specific classes and or properties in a superclass or a single class with the properties that I just need and use that as my model....
Here is the excerpt from the author:
EntityFramework is initially a one to one mapping of classes to tables, but you can create a model that better represents the entities in your application no matter how the data is stored in relational tables.
What I think the author may have been hinting at is the concept of complex models. Let's say, for instance, that in your Database you have a Customer Table and an Address Table. A one to one mapping would create 2 model items, one Customer class and one Address class. Using complex model mapping, you could instead create a single Customer class which contained the columns from both the Customer Table and the Address table. Thus, instead of Customer.Address.Street1 you could refer simply to Customer.Street1. This is only one of many cases where you could represent a conceptual model in code differently than the resulting data in storage. Check out the excellent blog series Inheritance with EF CodeFirst for examples of different mapping strategies, like Table Per Hierarchy (TPH), Table Per Type (TPT), Table Per Concrete Class (TPC). Note that even though these examples are CodeFirst, they still apply to Entity Framework even if the initial models are generated from a Database.
In general, if you use DatabaseFirst and then never modify the resulting entities, you will always have a class in code for each table in the database. However, the power of Enity Framework is that it allows you to more efficiently work with your entities by allowing these hybrid mappings, thus freeing you to think about your code without the extra burden of your classes having to abide by rigid SQL expectations.
Edit
When the Database-First or Model-First entities are generated, they are purposely generated as partial classes. You can create your own partials which extend the classes that are generated from Entity Framework without modifying the existing class files. If the models are re-generated, your partial classes will still be intact. Granted, using partials means that you have the Entity Framework default behaviors as well as your extended behaviors, but this isn't usually a huge issue.
Another option is that you can modify the TT files which Entity Framework uses to generate your models, ensuring that your models are always regenerated in the same state.
Ultimately, the main idea is that just because the default behavior of Entity Framework is to map the database to classes 1:1, there are other options and you are never forced into something that isn't efficient for your project.

How to use entity framework in other modules?

I am currently developing project using C# MVC and entity framework, I want to use the entity framework in other modules ,
i.e security module , Utility module ,
i want to call the db using the entity frame work, how do i do this ?
i am new to this are please explain in detail, idea is to break the project into presentation layer, business layer and data access layer..
i don't know how to archive this.
Try this way,
There are three ways to work around entity framework, Database First, Model First & Code First.
Database First: If you already have database, then entity framework can generate a data model that consists of classes & properties that correspond to existing database objects such as tables & columns.
The information of database structure, conceptual data model & mapping between them is store in the xml in an .edmx file.
Model First: If you don't have database, you can start creating model using vs entity framework designer. This approach also use the .edmx file.
Code First: In this approach, we don't need .edmx file. Mapping between store schema & conceptual data model is represented by code, handled by code convention & special mapping API.
Here I have used the Database First approach.
In order to use the Dal class lib, add the reference in the business logic layer and initialize the entities class. For example
Find the entity framework object.
Initialize the entity framework object in other class lib.
FrameworkEntities entities = new FrameworkEntities();
Please let me know, if you want to use model first or code first approach.
Get started from the below link for the Entity Frame Work
http://msdn.microsoft.com/en-US/data/ee712907?

Using EF and MVC together

I would like to use Entity Framework 5 from which I can use one MVC Model that can span two or more databases.
Is this possible?
In other words, have one EF model that can use two or more databases. Because with MVC, you can only use 1 model in a View. Some of the data with some of the Views can come from different databases. In order to use the model binder in MVC and map it to EF 5 columns, I would need to accomplish this.
ASP.NET MVC is NOT dependent on Entity Framework.
ASP.NET MVC is a framework for building web application that stick with the Model View Controller pattern. It is not bounded to Entity framework. It can work with any data access technologies like LINQ2SQL / Entity Framework / Pure ADO.NET etc.. that means you can develop MVC application with or without using Entity Framework.
I assume you want to get data from 2 different databases and load a model object. You can do that by writing a select query which gets data from 2 databases and put that in a Stored procedure and put that proc in your database which your DbContext is communicating with. Then execute the stored proc and load the Model object.
a sample procedure which gets data from 2 databases
CREATE PROCEDURE GetCustomer(#id int)
AS
BEGIN
SELECT C.ID,A.DateReceived
FROM FirstServerName.DbName.dbo.Customer C
INNER JOIN SecondServerName.DbName.dbo.Applications A
ON A.CustomerID=C.CustomerID
AND A.CustomerID=#id
END
To execute the stored proc with Entity framework, you can use Database.SqlQuery method
var idParam = new SqlParameter { ParameterName = "#Id", Value = 414};
var result = context.Database.SqlQuery<Customer>
("exec GetCustomer #Id", idParam).ToList();
This will execute your proc and load the data to an instance of Customer class, assuming the result set structure and your model class structure look similar.
You may need to adjust the permissions of the stored proc to read data from the relevant databases /tables.
What Shyju is saying is that MVC doesn't care or know anything about your Entity Framework data model or database. As such, the idea that an MVC model can span two databases is like saying an airplane can span two hammers.
As above the M in MVC is whatever you want it to be. Microsoft don't specify what Model actually is. It certainly doesn't have to be an EF Model (although some code samples from MS use that as an example)
I'd suggest that M should be a ViewModel and should be unrelated to your data layer. Then use a tool like Automapper to map from a domain model to a ViewModel. The ViewModel encapsulates the data you want to show and any specific web view specific information that you want to display. Then when you post back the ViewModel you can use that to update the domain models appropriate fields etc and persist that to both databases. This is a good article on the subject of ViewModels http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/

How to get data from 2 entities in MVC ?

I am developing MVC application and using razor syntax. I have used model first method.
I have two entities, Customer and Lead. Lead is inherited from Customer.
When IsActive property is true then Customer treated as a Lead, otherwise it will be a customer.
Please check edmx file image.
Now, In regular entities we just deal with single entity and single table.
In this case how can I handle , Save and Load process. beacuse I have to store and load the record from 2 tables of DB.
Is Regular Index View will work here ?
When using inheritance in the Entity Framework you will have a single DbSet on your DbContext that exposes your hierarchy. In your database you have several options for configuring your table structure. For example you can use:
Table per Hierarchy
Table per Type
Table per Concrete type
(See this blog for a nice explanation: Inheritance in the Entity Framework.
In your queries however, you don't have to think about this. Your queries will have the following structure:
var leads = from l in dbcontext.Leads.OfType<Customer>()
select l;
The OfType() filters your collection to a subtype in your hierarchy. If you skip the OfType you will get both customers and leads in your resulting query.

Resources