I am trying to list some data from a news section. I have two tables. News and NewsCategory
This is my model classes
public class News
{
public int NewsId { get; set; }
public string Name { get; set; }
public int NewsCategoryId { get; set; }
public virtual NewsCategory NewsCategory { get; set; }
}
public class NewsCategory
{
public int NewsCategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<News> News { get; set; }
}
public class NewsDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
}
public DbSet<News> News { get; set; }
public DbSet<NewsCategory> NewsCategory { get; set; }
}
This is also working, when I in my controller fect the data, with the exception of one thing. When I fect my news, I do not have a reference to my Category.
My controller code:
var news = _db.News.ToList();
This outputs :
[
{
"NewsId": 1,
"Name": "ghdfgd",
"NewsCategoryId": 1,
"NewsCategory": null
},
{
"NewsId": 2,
"Name": "gdfgdf",
"NewsCategoryId": 1,
"NewsCategory": null
}
]
As you can see, NewsCategory is empty. Although it is not:)
What am I missing?
It's because you are lazy loading the navigation properties.
Look into this article.
Just do this:
var news = _db.News.Include(n => n.NewsCategory).ToList();
Related
How do I map table value functions in Code with Entity Framework 6.3? I'm trying to a DB Context in code with an existing database, because EDMX is currently not supported in ASP.NET Core 3. I've tried setting up my DbContext clasee as below. I can successfully query the Grade table. But when I try to query my function "fn_GetCatgeories", I get the following error: No EdmType found for type 'WebApplication6.Data.ApplicationContext+fn_GetCategories'.
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories
{
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new FunctionsConvention<ApplicationContext>("dbo"));
base.OnModelCreating(modelBuilder);
}
[DbFunction("ApplicationContext", "fn_GetCategories")]
public IQueryable<fn_GetCategories> GetCategories(Nullable<System.DateTime> month)
{
var monthParameter = month.HasValue ?
new ObjectParameter("Month", month) :
new ObjectParameter("Month", typeof(System.DateTime));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<fn_GetCategories>(string.Format("[0].{1}", GetType().Name, "[fn_GetCategories](#Month)"), monthParameter);
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
}
This works:
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories_Result
{
[Key]
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
public DbSet<fn_GetCategories_Result> fn_GetCategoriesSet { get; set; }
public List<fn_GetCategories_Result> fn_GetCategories(DateTime month)
{
var m = new SqlParameter("Month", DateTime.Now);
return this.fn_GetCategoriesSet.SqlQuery("select * from dbo.fn_GetCategories(#month)", m).ToList();
}
I have made one model so far and added controller using EF, and made some list of books
public class Books
{
public string ImageUr { get; set; }
public string BookTitle { get; set; }
public string ShortDescription { get; set; }
public decimal Price { get; set; }
public string Author { get; set; }
public int ID { get; set; }
}
public class BooksDBContext : DbContext
{
public DbSet<Books> Book { get; set; }
}
and im displaying that list in this action:
public ActionResult Books()
{
return View(db.Book.ToList());
}
and my question is how can i make another model or database that will be passed into this action (viewpage for news about new books for example):
public ActionResult News()
{
View(db.News.ToList());
}
and the model for news to be something like this:
public class News
{
public string Title{ get; set; }
public string Subtitle { get; set; }
public string Content{ get; set; }
public int ID { get; set; }
}
Well maybe you can try out a viewmodel. When I started learning ASP.NET MVC I did the tutorial Working with data and learned a lot about entity framework and ASP.NET MVC! I will give you a link. ASP.NET working with data
For your solution some code:
UPDATE You will need some virtual properties in your classes to define the relationships: we have a one to many relationship because book can have more news items and news can only have one book.
public class Book //change your class name to book
{
public string ImageUr { get; set; }
public string BookTitle { get; set; }
public string ShortDescription { get; set; }
public decimal Price { get; set; }
public string Author { get; set; }
public int ID { get; set; }
public int NewsId { get; set; }
public virtual ICollection<News> News { get; set; }
}
public class News
{
public string Title{ get; set; }
public string Subtitle { get; set; }
public string Content{ get; set; }
public int ID { get; set; }
public int BookId {get; set; }
public virtual Book Book { get; set; }
}
if your want to use a viewmodel then add a new folder named viewmodels and add a new class
public class BookNewsViewmodel //viewmodel of book and News :)
{
public IEnumerable<Book> Books { get; set; }
public IEnumerable<News> News { get; set; }
}
In the DbContext
namespace yourProject.DAL
{
public class yourProjectContext : DbContext //this is a DbContext!
{
public yourProjectContext () : base("yourProjectContext") //A constructor
{
}
public DbSet<Book> Books { get; set; } //make a DbSet of your classes
public DbSet<News> News { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Pluralize your tablenames from Books to Book and from Newss to News :)
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
In your controller:
With viewmodel
public ActionResult BookNewsIndex()
{
var viewModel = new BookNewsViewmodel();
viewModel.Books = db.Books
.Include(n => n.News)
return View(viewModel.ToList()); //return your data.ToList() to your view
}
Without a viewmodel
public ActionResult BookNewsIndex()
{
var data = db.Books.Include(n => n.News);
return View(data.ToList()); //return your data.ToList() to your view
}
In your View named BookNewsIndex you can do this. I am not sure about this but you can give it a try
#model yourproject.ViewModels.BookNewsViewmodel for your viewmodel
OR
#model IEnumerable<yourProject.Models.Book> without viewmodel
with viewmodel
#model.Books.ShortDescription
#model.News.Subtitle
without viewmodel
#Model.First().ShortDescription get something from your book!
#Model.First().News.First().Subtitle get something from news!
In part 7 of the tutorial he will use a viewmodel
I hope this will help you!
This has nothing to do with MVC, but with Entity Framework.
You'll have to add the DbSet for News:
public class BooksDBContext : DbContext
{
public DbSet<Books> Book { get; set; }
public DbSet<News> News { get; set; }
}
Relatively new to MVC and can't figure out how to pass data from multiple models into a single view. I know I need to use a view model, but I can't figure out what to do in the controller.
Models:
public class Child
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ChartNumber { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string City { get; set; }
public string State { get; set; }
[Display(Name = "Zip Code")]
public int ZipCode { get; set; }
public string Ethnicity { get; set; }
public string Referral { get; set; }
[Display(Name = "Recommended Re-evaluation")]
public bool ReEval { get; set; }
[Display(Name = "Hearing Aid Candidate")]
public bool HaCandidate { get; set; }
[Display(Name = "Fit With Hearing Aid")]
public bool FitHa { get; set; }
public virtual List<ChildEval> ChildEvals { get; set; }
}
public class ChildEval
{
[Key]
public int ChildEvalId { get; set; }
public DateTime Date { get; set; }
public int PtaRight { get; set; }
public int PtaLeft { get; set; }
public int UnaidedSiiRight { get; set; }
public int UnaidedSiiLeft { get; set; }
public int AidedSiiRight { get; set; }
public int AidedSiiLeft { get; set; }
public int ChartNumber { get; set; }
public virtual Child Child { get; set; }
}
}
DbContext
public class UnitedContext : DbContext
{
public UnitedContext() : base("name=UnitedContext")
{
}
public System.Data.Entity.DbSet<United.Models.Child> Children { get; set; }
public System.Data.Entity.DbSet<United.Models.ChildEval> ChildEvals { get; set; }
}
ViewModel:
public class ChildViewModel
{
public class Child
{
public string FirstName { get; set; }
}
public class ChildEval
{
public int PtaRight { get; set; }
}
}
ViewModelController? :
public class ViewModelController : Controller
{
//
// GET: /ViewModel/
public ActionResult Index()
{
return View();
}
}
}
I'm stuck on how to create the controller for the viewmodel and how to actually get the data into the view. Any help would be greatly appreciated!
Don't have a controller called ViewModelController. Controller is the handler between database and the view. Therefore the name of the controller should tell the programmer what kind of data the controller is controlling. By default, it also indicates the subsite you are in your web application ( ViewModelController would yield http://mysite/ViewModel/ ).
Since you are handling children, I'm calling it ChildrenController for now.
Generally a good idea is to wrap your 2 models into one viewmodel and work with that. In this case Model != ViewModel, model is the database model of the entity while ViewModel is the one that's passed to/from the view.
public class Child
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class SomeOtherModel
{
public int ID { get; set; }
public int SomeInteger { get; set; }
public int SomeOtherInteger { get; set; }
}
public class ChildViewModel
{
public Child Child { get; set; }
public SomeOtherModel SomeOtherModel { get; set; }
public ChildViewModel(Child child, SomeOtherModel s)
{
Child = child;
SomeOtherModel = s;
}
}
In your controller
public class ChildrenController : Controller
{
//
// GET: /Children/
public ActionResult Index()
{
Child child = /*Fetch the child from database*/;
SomeOtherModel someOther = = /*Fetch something else from database*/;
ChildViewModel model = new ChildViewModel(child,someOther);
return View(model);
}
}
View:
#model ChildViewModel
#Html.EditorFor(model => model.Child.FirstName)
#Html.EditorFor(model => model.Child.LastName)
Should T be a for example Customer or CustomerViewModel ?
The annotations bound to Mvc namespace are on the ListViewModel so actually I could pass the Customer object. What do you think?
public class ListViewModel<T>
{
[Required(ErrorMessage="No item selected.")]
public int[] SelectedIds { get; set; }
public IEnumerable<T> DisplayList { get; set; }
}
UPDATE
[HttpGet]
public ActionResult Open()
{
IEnumerable<Testplan> testplans = _testplanDataProvider.GetTestplans();
OpenTestplanListViewModel viewModel = new OpenTestplanListViewModel(testplans);
return PartialView(viewModel);
}
public class OpenTestplanListViewModel
{
public OpenTestplanListViewModel(IEnumerable<Testplan> testplans)
{
var testplanViewModels = testplans.Select(t => new TestplanViewModel
{
Name = string.Format("{0}-{1}-{2}-{3}", t.Release.Name, t.Template.Name, t.CreatedAt, t.CreatedBy),
TestplanId = t.TestplanId,
});
DisplayList = testplanViewModels;
}
[Required(ErrorMessage = "No item selected.")]
public int[] SelectedIds { get; set; }
public string Name { get; set; }
public IEnumerable<TestplanViewModel> DisplayList { get; private set; }
}
public class TestplanViewModel
{
public int TestplanId { get; set; }
public string Name { get; set; }
}
public class Testplan
{
public int TestplanId { get; set; }
public int TemplateId { get; set; }
public int ReleaseId { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public Template Template { get; set; }
public Release Release { get; set; }
}
T should ideally be a view model. Having a view model referencing domain models is some kind of a hybrid view model, not a real one. But if you think that in this specific case the domain model will be exactly the same as the view model then you could keep it as well.
I have the following entity model:
public class Project
{
[Key]
public int ProjectID { get; set; }
public string Title { get; set; }
public string Slug { get; set; }
public string Content { get; set; }
public string Category { get; set; }
public string Client { get; set; }
public int Year { get; set; }
// more attributes here...
}
I would like to prepare a view model (specific for my view). Here is the view model:
public class ProjectListViewModel
{
public IEnumerable<ProjectInfos> ProjectList { get; set; }
public PagingInfo Paging { get; set; }
public class ProjectInfos
{
public string Title { get; set; }
public string Slug { get; set; }
public string Content { get; set; }
public string Category { get; set; }
public string Client { get; set; }
public int Year { get; set; }
}
public class PagingInfo
{
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
}
}
In my controller, I would like to prepare the view model by filling it with 2 different objects:
List of projects
Paging information
Here is my controller:
public ViewResult List(string category, int page = 1)
{
IEnumerable<Project> projectList = m_Business.GetProjects(category, page, 10);
PagingInfo pagingInfo = m_Business.GetPagingInfo(category, page, 10);
// Here I need to map !!
ProjectListViewModel viewModel = .....
return View(viewModel);
}
So how can I proceed in my controller? I know we can use automapper to map from one object to another but here I need to map from two objects into a single one.
Thanks.
You can extend AutoMapper to map multiple objects.
Here is a blog which provides some sample cope.
Then you can use code like this:
var personViewModel = EntityMapper.Map<PersonViewModel>(person, address, comment);