Ok So I am just simply needing good instructional pages on how to design a Class for retrieving data from the database.
I can find information all over on how to take an existing database and create an Entity Framework from it but I am trying to do code first.
I am able to insert Data (although I am not 100% sure how that is working) I just cannot seem to figure out how to pull the data from the database using the class(Model) that is created and display that data on a Razor page.
I have no problem with doing the studying and learning this but I am having a terrible time at finding good information that will just do a true walk through of this process.
Once again I am not looking for the Entity Framework.
Thank you for all of the help you can provide.
There is a lot of tutorials out there in the internet. Here is a small example to pull your data from table and show in the view.
Assuming you have a model class called User like this
public class User
{
public int ID { set;get;}
public string FirstName { set;get;}
}
Add properties like this to your DataContext class for each of your model entities. The property is of type DbSet.
public class YourDataContext: DbContext
{
public DbSet<User> Users {set;get;}
}
Then in your controller action method, you can create an instance of your DBContext class and access its Users property. Pass that to our view.
public class UserController : Controller
{
public ActionResult Index()
{
YourDBContext db=new YourDBContext();
var users=db.Users.ToList();
return View(users)
}
}
Have an index.cshtml view like this under Views/User folder.
#model IEnumerable User
#foreach(var user in Model)
{
<p>#user.FirstName</p>
}
Related
I'm writing an app in MVC 5 right now. I've made MVC app(for iOS) some time ago, but honestly i'm a little bit confused right now. I tried to find some info about this pattern, but it seems that there are many approaches.
My app uses external database operating on JSON format. I have bunch of methods in Api class that return objects filled with data from database. In my opinion this Api class is basically model, but i am not sure.
Model:
//Model
public class UserModel
{
public string Name { get; set; }
public string Lastname { get; set; }
}
Api class(Model?):
public class Api
{
public UserModel GetUserData()
{
UserModel model = new UserModel();
//code connecting to DB and filling UserModel object
return model;
}
}
Controller:
//Controller
public ActionResult Index ()
{
UserModel model = new UserModel();
Api api = new Api();
model = api.GetUserData();
return View(model);
}
View:
#*View*#
#model application.Models.UserModel
#Model.Name
#Model.Lastname
And my last question. Where should i put methods like loginuser, delete user:
public void DeleteUser(UserModel model)
{
//code deleting user
}
Should it go to model or controller? What i think is - if it will be used multiple times in different places i should put it in model, otherwise it should go to controller.
Thanks in advance.
Your Api class is not a model, the model classes must be entities of your domain. Your domain is the core of your business, for example, if your are making a School Application, your models/entities are: Student, Teacher, Discipline ...
So your Api belongs to your infrasctucture layer, and all classes with database access responsability.
Your controller's must only orchestrate the workflow, for example:
private readonly api;
public HomeController()
{
this.api = new Api();
}
public ActionResult Index ()
{
var model = api.GetUserData();
return View(model);
}
Your Api probably will be used on other Actions, so you can make a private field and initialize it from constructor. But the best approach is to use an IoC container.
The LoginUser must be a action on your Controller, but the business rule could be on other layer of your project, so it can be reusable. For example:
public ActionResult Login(string login, string password)
{
var user = api.GetUserByLogin(login);
if(user == null)
{
ViewBag.ErrorMsg = "There is no user with this login";
return View();
}
//userService is a class responsible for business rules for users
var isSuccess = userService.LoginUser(login, password);
if(isSuccess)
return RedirectToAction("Index", "Home");
ViewBag.ErrorMsg = "Password is incorrect";
return View();
}
Be careful because the ASP.NET MVC still have the concept of ViewModels. That are classes where we use to show data in our Views. In our school application, for example, we could have a View which is necessary to show a Discipline with all students enrolled, and what professor. So we need to use information of 3 entities, in that case we make a ViewModel to show all this information together.
I have two database classes as defined below:
public class TopDate
{
[Key]
public int DateId { get; set; }
public DateTime Date { get; set; }
}
public class TopSong
{
[Key]
public int SongId { get; set; }
public string Title { get; set; }
public int DateId { get; set; }
}
where DateId is foreign key to TopSong
I am creating a controller through which i can create, delete or edit these database values.
When i right click on controller class and add controller i can only select one of the two classes defined above. Is there a way to make 1 controller to handle database updates to both these tables on one page?
Error Image:
Your controller should not be dealing directly with domain objects (meaning those things that are directly associated with your database). Create a ViewModel that contains the properties that you need, use your service layer to populate the ViewModel and your controller will use that as the Model for its base. An example of your ViewModel could be something like the following given your description above:
public class MusicViewModel
{
public int SongId {get;set;}
public string Title {get;set;}
public IEnumerable<DateTime> TopDates {get;set;}
}
This view model would contain a list of all dates that a specific song was a Top Song.
The objects you showing (code) are database classes (so called domain objects).
What you need to do is to define a view model, a standard ASP MVC practice:
you define a class, that is tailored for specific view and only containing data relevant to that particular view. So you will have a view model for a view that will create a song, another that will update it etc.
Actually situation you describing is classical situation to use view models. Using domain objects in the views, however, is really really bad practice and prone to more problems than you want to deal with.
Hope this helps.
I have a standard model set.
I have a base context class that inherits from dbcontext to add some features I needed.
public class MyContext : DbContext
{
public void MyFeature() {
}
}
I then have my actual Data Context:
public class DataContext : MyContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
I want to use the scaffolder built in when you create a controller, but I get an error "Unsupported Context Type"
If I change the datacontext to just inherit from dbcontext directly it works, but at this point I have alot of stuff that uses the added features, so changing the inheritance cant be done without commenting out all that stuff. And I have of course simplified down the features, it is actually quite alot of stuff, so adding it directly into the datacontext would be alot of work, plus the scaffolder should be smart enough to see that the datacontext is a dbcontext.
How can I use the scaffolder with my datacontext?
Why don't you use Composition?
If your feature really is just needed as lets say a few methods needed in those objects I would put those methods in a separate class called ContextDetails - something along those lines and have DataContext contain a ContextDetails like so:
//Changed MyContext to ContextDetails
public class ContextDetails
{
public void MyFeature()
{
//Do something
}
}
public class DataContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public ContextDetails DbDetails { get; set; }
}
And if the ContextDetails object needs information about the DataContext/DbContext it's in pass the DataContext/DbContext into a method or even the constructor.
If you don't like Composition for this problem maybe you want to use an Interface. If that's the case check out http://www.codeproject.com/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C
The context class must inherit from System.Data.EntityDbContext which provides facilities for querying and working with entity data as objects
The best reason I could find for why the inheritance is not working in your example.
EDIT:
I read my answer and realized DBDetails might not be the best name but you get the idea. Extract the implementation and use it as a separate entity. Good luck!
i think first you should install entity framework 4.0 then i think definitely it's working please try this.
I seen many examples of edit actions in asp.net mvc 3 and that's why I confused. For example, how does work UpdateModel and TryUpdateModel methods? Or how to implement edit action if I want to update not all fields?
Could anyone give me a link about implementing edit action in asp.net 3?
Best way to update only desired fields is create separate view model for it. For example, imagine you've got user class like this
public class User
{
public int Id {get;set;}
public string UserName {get;set}
public bool IsAdmin {get;set;}
}
And suppose you do not wish to let user supply value for IsAdmin property. You create view model like this (no IsAdmin field)
public class EditUserViewModel
{
public int Id {get;set;}
public string UserName {get;set}
}
And the edit action pseudo something
public ActionResult Edit(EdituserViewModel model)
{
If(ModelState.IsValid)
{
User user = _repository.GetUser(model.Id);
user.UserName = model.UserName;
_repository.Update(user);
return RedirectToAction("Index");
}
return View(model);
}
This way, there's no possiblity to supply IsAdmin from client side. You may also want to take a look at AutoMapper and Jimmy Bogard's blog for mapping view models to domain models. Jimmy's got the post about using ViewModels and AutoMapper in asp.net mvc too.
For example, in an IDE application, say for C#, there are 2 views ClassView and TextView.
In ClassView we need to display the Class information in a hierarchical manner, where as in TextView the code for that Class is shown.
The ClassView needs to query for classes, methods, properties, fields, etc. whereas the Text View queries lines in the code.
Both the views are editable. Change in one view should be reflected in the other view too.
So Class View requires one model and Text View requires another but the underlying data is the same.
Is there a design pattern to solve such a problem?
Thanks in advance.
Certainly an MVC model can be hierarchical. If your data is all contained in a single file, maybe you don't really need multiple models for your application? How about:
namespace MyNamespace
{
public class CodeFile
{
/// <summary>
/// A list of contained classes for the Class view
/// </summary>
public List<CodeClass> Classes { get; set; }
public CodeFile()
{
Classes = new List<CodeClass>();
}
public string ToString()
{
// send output to Text view
}
}
public class CodeClass
{
public string ClassName {get; set;}
public List<CodeProperty> Properties {get; set;}
public List<CodeMethod> Methods {get;set;}
public CodeClass(string className)
{
ClassName = className;
Properties = new List<CodeProperty>();
Methods = new List<CodeMethod>();
}
}
public class CodeMethod
{
public string MethodName { get; set; }
}
public class CodeProperty
{
public string PropertyName
}
}
Model View Controller :)
The mistake in your question is that your data is actually mapped on your model.
You can have 2 views (classview and textview) and they both works with one single common model. Controller can update one view when another one changes the model.
You tagged it yourself with MVC... The underlying data is the model, the Class View and Text View act as views/controllers. The model sends out events to its views, to make sure that changes in one view are reflected in the other.
There's nothing in MVC architecture to prevent writing multiple model hierarchies which interact with the same underlying data store.
You would just have Controllers/Views which interact with Model A, and different Controllers/Views which interact with Model B.