Partial loading of Entity Framework entities and passing them to presentation layer - asp.net-mvc-3

If I want to select only few columns when retrieving data for an EF entity and cast them to the Entity type, I am not able to do that because it throws an error as mentioned in this post
The entity cannot be constructed in a LINQ to Entities query. I don't want to select all the columns, because I need only few of them. I can use anonymous types, but if I am using repository pattern and want to encapsulate all data access code in repository object and pass strongly typed object collection to the controller (not an anonymous object collection), how can I achieve that? Is the only option to define a DTO object for every subset of the properties for the EF entity? I know there is a risk of losing data with partial loaded entities, but if I am ready to take the risk and want full control over data updates, is that not possible?
for example I would like the "ProductRepository" method signature to be like this
public IEnumerable<Product> GetProducts(int categoryID) //selection of subset of data
and I want to pass this product collection from the controller to the view (in ASP.NET MVC project) and in the view I want to have strongly typed model (with intellisense) object. Is this possible? if not, I may have to reconsider using EF for my project due to this limitation. I am using EF 4.1 version.

Yes the option in this case is special object for each subset of properties you want to select. You can call the object DTO because it is just a result of the projection. This is the correct approach because if your UI doesn't need other properties of entity type it is correct to pass it only specialized ViewModel.
Another more complex (and worse) option is selecting anonymous type inside your Linq-to-entities query, calling ToList and after that construction the real entity type. Partial entity selection is not allowed and projecting to mapped entity types is not allowed as well. That is the reason why you have to use such a cumbersome approach. Example:
// Select anonymous projection
var query = from x in context.Entities
where ...
select new { ... };
// Repopulate entity type
var reultSet = query.ToList().Select(x => new Entity { ... });

Yes, what you want is totally possible using viewmodels instead of entities. Here is example controller code:
var productEntities = productRepos.GetProducts(6);
var productViewModels = Automapper.Mapper
.Map<IEnumerable<ProductViewModel>>(productEntities);
return View(productViewModels);
Your view model will have only the properties it needs for the view. Check out automapper.

Related

linq to sql, how to define DataContext without specifying Table properties

My intent is to create a generic (not in C# meaning) database model for Windows Phone using linq to sql. User of such model should be able to pass an array of his data object types (classes marked with Table attribute) to model's contstructor, and then model should take care about adding related tables to database and provide API for CRUD operations.
But then I've found out that in order to add tables to database, your data context (class inherited from DataContext class) have to declare each table as a property! That's embarrassing. Does this fact mean that my idea is not implementable? Because I obviously cannot add properties to my DataContext-based in the runtime.
So my question is, am I right in my judgments? If yes, are there some workarounds to solve this issue?
Thanks in advance.
EDIT: better question tagging, for somebody finally notice this.
You do not need to use a strongly typed DataContext (a class inheriting from DataContext and declaring properties for each table). You can do something like the following instead
var context = new DataContext("connection string", new AttributeMappingSource());
var table = context.GetTable<T>();
where T is some type marked with the Table attribute.

Using LINQ to compare a searchstring with the value of all the string properities of a EF class

In my ASP.NET application I have an EF Product class (derived from Product DB table) and I want to perform search functionality on its string fields by using inline LINQ.
Since I predict the name and amount of the fields (properties) will change I do not want to strongly couple my code with the table definition. How can I compare the values of all the fields in the table with a search string by iterating through all table fields (properties)?
I know one option is through reflection, is there any easier and more immediate way to fulfill this task?
In the end, your EF class is still just a normal .NET class. Unless EF explicitly provides some library for looping through properties (it doesn't that I know of), you'll still need to use reflection to do this.
var properties = typeof(Product).GetProperties(BindingFlags.Instance);
foreach (var property in properties)
{
...
}

MVC3 (Models) ...what is the right way to display complex data on the view?

I’m having a philosophical problem with understanding how to use Models on MVC3.
I believe the problem lies from the fact that I come from WebForms :--)
Let's say I have 10 tables on my DB and as expected when I get them into my EF4, I get those Entity classes that represent the tables (and all their FK integer values).
When I want to display data on the View, I cannot display a select * from table because those FK integers means nothing to my users …and also because some data lies on related tables.
So my understanding is that I can create a Stored Proc, create a Complex Type that represent the actual data to display, coming from separate tables via different SQL joins.
QUESTION 1:
On the view, id MVC compliant to use as #model ..that Complex Type?
or shall I always use Models that are created on the Models folder? And if so, does that mean that I have to replicate the Complex Type on a new model inside the Models folder?
Question 2:
Is this the right way …to create specific SP to collect data that will be displayed or ..is it better to use linq and lambda to be applied to the EF4 Types that come from importing the DB into the EMDX designer.
Thoughts ??
FP
The correct way is to always define view models. View models are classes which are specifically tailored to the needs of a given view and would be defined in the MVC application tier. Those classes would contain only the properties that would be needed to be displayed by the view. Then you need to map between your domain models (EF autogenerated classes?) and the view models.
So a controller action would query a repository in order to fetch a domain model, map it to a view model and pass this view model to the view. Top facilitate this mapping you could use AutoMapper. A view shouldn't be tied to a domain model and always work with a view model. This works also the other way around: a controller action receives a view model from the view as action argument, maps it to a domain model and passes this domain model to the repository in order to perform some action with it (CRUD).
So a view model could be a class that is mapped from multiple domain models or multiple view models could be mapped to a single domain model. It all depends on how your domain looks like and how do you want to represent the information to the user.
As far as validation is concerned, I distinguish two types: UI validation and business validation. As an example of UI validation is: a field is required, or a field must be entered in a given format. A business validation is : the username is already taken or insufficient funds to perform wire transfer. UI validation should be done on the view models and business validation on the domain models.
I'm not sure why you need to use a stored proc, LINQ to Entities is able to generate complex types without needing to create stored procs (in most cases). You select subsets of data, just like you would with regular SQL.
As Darin says, the use of a View Model is appropriate for situations where you have a lot of complex data that isn't represented by a single entity. This View Model would contain multiple entities, or even multiple collections of entities. It all depends on how your data needs to be consumed.

How to get data to my view that comes from more than one object?

So I have read some of the similar asked questions, but I don't know if the right questions were asked. It appears there are different ways to get data from multiple entities passed into your View Model, but I want to go about it the correct way.
I basically have 2 entities available in my controller, and I need to pass different information from both entities to my view. I have read about creating a SomeNameViewModel class that would be instantiated in my controller ViewResult method. With the SomeNameViewModel object assigning the data into a single object to pass to the View Model
Example:
public ViewResult List()
{
var vm = new SomeNameViewModel {
products = _prodRepo.All();
catName = <Some Expression>;
return View(vm);
}
But is this the best practice way to go about this?
I am using Nhibernate: So would this be better handled in my Fluent Mapping so that I have access to the other entity through the one-to-one mapping?
Using a model per view is a common (and good) way to go about providing data to your views. View models can encompass values from more than one entity type and may contain ancillary data as well. You might want to also consider using view-specific models for any entities contained in your view model to further isolate your view from your domain objects. This way you can provide to your view exactly the data they need and no more and, if your domain model changes, you may be able to only modify how the view-specific model gets updated from the domain model rather than propagating the change throughout your views.

Linq to Entities, EntityReferences and DataGridViews

I am trying to select certain fields from my entity to be used as the datasource for a datagridview, but I haven't been able to make it work. Is such a thing possible? For example, I have a Customers entity that contains several entityreferences. I want to take fields from the customers entity and from within those entityreferences and display them in the datagridview. I haven't been able to come up with a Linq query to accomplish this, and even when you simply use the entire entity as the datasource the fields within the entityreferences are not displayed. Any idea what I am doing wrong? Thanks for the help.
from customer in context.customers
select new
{
Name = customer.Name,
City = customer.Address.City
}
that will create a custom object and you can see the second property is referencing an entity field on the primary entity.. basically just transform the data to a new object and bind the enumerable generated to the grid.
sorry if this is a little mumbled, typing on my phone.
Caveat: This is not tested with entity framework references.
When using object data sources you can reference properties of object references, but you must first cast the object:
<asp:Label ID="lblCity" runat="server" Text='<%# ((Customer)Container.DataItem).Address.City%>'></asp:Label>
Could this be your problem accessing properties of the entity references?

Resources