how do I configure a (MVC using entity framework) controller in a web api project - api

I have a MVC 4.0 Web API project and I have already added the model of my database to it so I have the files:
.edmx
.Context.tt
.context.cs
.edmx.diagram
I'm trying to figure out how to add a controller after I've created my entity framework model.
It's asking for the Model Class and Data context class.
I'm not sure what they are in my solution.
can anyone give me a hand?

It depends what you are trying to do...
1. you can create an empty controller and then you do not need to select the Model and Context. you write the Add/Edit/Delete functions yourself and their views.
2. you can create a controller with read/write action and views - this way you get these functions Add/Edit/Delete + views done for you automatically:).
The Context is (as I understand it) the reference to the database.
if you havent already you should add your model classes that you want to create as tables in the database to the YOUR-PROJECTNAMEContext.cs file under DAL folder. this will create the tables for you (if I didn't forget anything). you shoula add somethis like:
public DbSet<Note> Notes { get; set; }
where Note is your class for example and Notes is your table name.
now if you want to create a Controller for you notes class in the model and let MVC to do for you the ADD/Edite/Delete function and views than your model is: Note and Context is YOUR-PROJECTNAMEContext.
Hope it will help.

Related

How to create an TextField with input history?

How to create a TextField is explained very well in a tutorial. But I am wondering how to store and retrieve the entered strings in a persistant way, that survives application termination and restart (something like a Bash history).
I will try to give you a very briefly answer
You need
a viewmodel class
a repository class
a database (room database is ideal)
an entity data class
a dao class
You should find more info about room database from jetpack libraries.
Of course are uncounted ways to implement this feature but it is in general the following way recommended.
You capture from your view the query string, may on submit.
In viewmodel you implement a method captureSearchQuery(query: String)
Also in viewmodel you implement a method for example retrieveSearchHistory() : Flow<List>
The repository class is your single source of true, is the layer between the data layer and the view layer, you implement also this two methods you need, captureSearchQuery and retrieveSearchHistory. In repository class you can may transform your data, for example is a good practice to have a separate data model for the data you display on the view from your room entity. There you can do this transformation for exmaple.
Now you have setup your room database you can insert and get the data you need.
The data should go this way:
View -> Viewmodel -> Repository -> Room database
View <- Viewmodel <- Repository <- Room database
The layer should never communicate otherway, (clean architecture) for example:
View -> Room database.
The above is my simplest explanation, I hope I help you

Expose only a part of my class

Lets say i have a Class User with multiple properties. I'm building a REST based App so in my homepage when I request for "user details" I need only a few properties from my User and rest from other classes. How do i write the class for the object which i would return for "user details" ?
My current design retrieves the needed properties from the class to build the JSON. I hope there is a better way to handle this.
I use Play Framework 2.0 with Java
If you don't want to expose whole business class User, I'll build a second class, a DTO. This class provides only the desired data to be transfered by REST API.
User user = new User("admin");
// Set other properties
UserDetailsDTO userDetailsDTO = new UserDetails(user); //<- Transfer userDetailsDTO
Or if "user details" are important for your application, maybe you should consider to create a UserDetails class and use it inside your User class by composition.
public class User {
Long id;
String name;
String address;
UserDetails userDetails; // Composition <- Tranfer userDetails
}
Note: example where don in Java
Looks like you need a Facade: http://en.wikipedia.org/wiki/Facade_pattern.
It is a simple pattern that helps you expose methods/properties from a multiple classes.
You can store references to objects in your Facade class and expose only those things you need.
There is an option of creating a View Model object, providing proper abstraction for the information required for that JSON.
More details about it here: http://en.wikipedia.org/wiki/Model_View_ViewModel
But this is typically used in the cases where view directly used in Views of the application. So careful analysis is required in use case mentioned above, since there is already JSON being created, creation of this View Model layer is really justified.

One view for various data from DB using repositories and UoW

I come from PHP and I really struggle with one model/one view approach when trying to display data from multiple entities in one View.
I've been learning asp.net mvc 4 with EF for about a month but still didn't find a good working solution to solve this issue.
My current approach is to access DB through Unit-Of-Work that creates Repository for every entity (table in DB)
public GenericRepository<Domain> DomainRepository
{
get
{
if (this.domainRepository == null)
{
this.domainRepository = new GenericRepository<Domain>(context);
}
return domainRepository;
}
}
then repository holds data from given entity (in this scenario DB),
public GenericRepository(PanelContext context)
{
this.context = context;
this.dbSet = context.Set<TTypeParam>();
}
and uses methods to filter data etc.
Using single repository to serve given view is not a problem because it uses only one model(entity).
When I'm trying to create model class (Combined) that holds ex. two models (Domain and Domain2) it's not a part of given context because that entity doesn't exist so it's pointless to use #model namespace.Models.Combined in a View.
Right now I'm using tuple to pull data from multiple repositories and use it to populate strongly-typed View but I know that there has to be a better way...
Basically the question is how to create an (abstract)? model class (entity)? that will hold data from multiple repositories and serve as viewmodel for a given View?
Big, big thanks for any help.
First of all the view model is not db entity. It's just a bucket used to send data to view. The controller populates that view model taking all the data required from the Model (repositories,services).
So if your view model is the Combined type, the controller will ask the repositories (which are NOT wrappers over EF, forget the examples you saw on asp.net mvc site or ef tutorials, they're wrong and teach you the repository anti-pattern) for data, wich may or may not be in the format neded by the view model. If it isn't, then create some extension methods in which you can map the objects returned by the repos to the view model.
So, the view model serves the View and it's populated by the controller with data from repositories. This way, the View is decoupled from the Model, because it knows only about the view model.

Zend Framework 2, Entity Manager, and Doctrine 2

Had a question about what best practice might be for the implementation of "convenience" queries. In reference to this article:
http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/#toc-install-doctrine-modules
It's clear that the entity manager is available in the IndexController - he does a findAll to list the entire contents of the database. What if, however, we added a "band" column to the database, mapped it out, and wanted to query all albums by the Beatles? What if the Beatles albums were used rather often throughout the codebase (weak example, but you get it).
The EM only seems to be available in Controllers, and Classes don't really seem to be aware of the service locator.
Would you simply break out DQL right in the controller, and repeat the DQL in every controller that needs it? (not very DRY)
Do we instead finagle some access to the EM from the Entity, or Model?
Doesn't seem as cut-and-dry as straight Zend_Db usage where you can fire queries anywhere you like, cheating to get things done.
Thanks for helping me cross over into a "real" ORM from the Table Gateway world.
Erm, Doctrine 2 is able to handle Relationships (e.g.: Bands to Albums and vice-versa)
The EntityManager can be made available in every single class you wish, as long as you define the class as a service. I.e. inside your Module.php you can define a factory like this:
// Implement \Zend\ModuleManager\Feature\ServiceProviderInterface
public function getServiceConfig() {
return array(
//default stuff
'factories' array(
'my-album-service' = function($sm) {
$service = new \My\Service\Album();
$service->setEntityManager($sm->get('doctrine.entitymanager.orm_default'));
return $service;
}
)
)
);
You can then call this class from every Class that is aware of the ServiceManager like $this->getServiceLocator()->get('my-album-service')
This class would then automatically be injected with the Doctrine EntityManager.
To be clear: All queries you'd do SHOULD be located inside your Services. You'd have your Entities, which are basically the DB_Mapper from Doctrine 2, then you have your Services, which run actions like add(), edit(), findAll(), findCustomQuery(), etc...
You would then populate your Services with Data from the Controllers, the Service would give data back to the controller and the controller would pass said data to the view. Does that make sense to u and answer your question?

MVC SPA w/o EF: You must write an attribute 'type'='object' after writing the attribute with local name '__type'

So I have a very normalized model, and I'm trying to create a single page application in MVC4 which wants to use an entity framework object. My problem is I can't manage to create an entity in EF with the kind of complex mapping that I need (I have checked multiple guides, but I can't seem to make one entity from multiple tables that contain different primary keys... I found a solution using updateable views, but that's really just pushing the abstraction down to the db layer).
So I thought I could create a POCO object using an EF query to create the object, then on insert/update/delete I could just take the POCO data and update the underlying 3 tables.
Well I hit a roadblock just trying to tweak an existing working controller to try and learn what's going on.
Let's imagine I have a working SPA controller that looks like this:
public partial class FooController : DbDataController<aspnetEntities>
{
public IQueryable<Foos> GetFoos() { ... }
}
I just change it a bit to return my new POCO data object Bar, which let's imagine has the exact same fields as Foo for the moment:
public partial class FooController : DbDataController<aspnetEntities>
{
public IQueryable<Bars> GetBars() { ... }
}
Over in FooViewModel.js I update the operation name to GetBars, and the type from
var entityType = "Foo:#Models";
to
var entityType = "Bar:#Models";
I hit my operation directly and I get:
OLD
<ArrayOfFoo><Foo><Property>true</Property></Foo></ArrayOfFoo>
NEW
<ArrayOfBar><Bar><Property>true</Property></Bar></ArrayOfBar>
So the controller looks like it's giving me what I expect, but when I try to put the whole thing together the SPA flashes up:
You must write an attribute 'type'='object' after writing the attribute with local name '__type'.
I'm guessing somehow I need to get type data into KO? I'm not sure where that might be however, I've been crawling through the JS for hours, but I'm not even clear on where it's failing. Any input would be greatly appreciated.
The problem you are experiencing is connected to the fact you are using POCO instead of the standard EF. It should be related to the webapi serializer that somehow doesn't recognize the class as serializable. Anyway it is a bug that will be removed in the RC. Give a look to this thread for workarounds:
http://forums.asp.net/t/1773173.aspx/1?You+must+write+an+attribute+type+object+after+writing+the+attribute+with+local+name+__type+