Using EF and MVC together - asp.net-mvc

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/

Related

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 access Stored procedure in Code First Model which return 6 or 7 table combine result

i am new in MVC and entity frame work and i want to create Code first entity frame work.
we have already created project in asp.net and we want to migrate in mvc. we have lots of stored procedure and some procedure return complex data combination of 10 to 12 tables...
As a Proof of Concept we wan't to develop 3 to 4 pages...
i have some question regarding new start.
1) Should i used entity frame work if yes then which is better entity frame work model
Database first
Model first
code first
2) how to integrate stored procedure in Code first model
3) in each page we have minimum 7 to 8 table result there... how i will handle in entity frame work.
this is my first project in mvc and entity framework please help me with appropriated answer.
first, this has nothing to do with MVC. this is purely a data access issue.
second, this is sort of missing the point of using entity framework. if the goal is to migrate away from stored procs that one thing, but to use EF and continue to execute the stored procs defeats the purpose of using a ORM like EF.
Instead for your procs I would stick with raw ADO.Net, or use Dapper.Net to convert the stored proc result sets into objects.
EF would be a better choice as your convert each proc into EF linq queries. It's not that you can't execute procs (or raw sql) from EF, but it doesn't make much sense. Especially with how you describe the procs.

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.

How to create model quickly&elegantly with Linq To Sql in asp.net mvc?

Ok straight to the issue. I can get object mapping to tables easily with Linq To Sql. For instance: class Product, class Order, class Order_Detail from Northwind. IMO, these 3 object have already met model's meet. But i can't put some useful attr([Required] [HttpPost]) on properties of them(except modifying design.cs, which is not recommended).Do i have to create ProductModels OrderModels with the same properties myself, and maybe some additional DAL-like classes to turn the linq2sql objects to models??
EDIT:
Even if i put design.cs and my models in the same namespace, how can i make two partial classes have the same properties??
Yes, you should create DTO's for each Linq to SQL model, it is not considered a good practice to pass Linq2Sql objects through your layers.
Optionally, look into to using Entity Framework Code First. It is stupid simple to use and you can add validation attributes directly to your POCOs, which are enforced on the data persistence side as well as the presentation side in MVC.
here's a good EF codefirst primer : http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

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

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.

Resources