Invalid object name dbo.Categories - asp.net-mvc

I am working on MVC 3. I am trying to create Simliar application as MVC Music Store but I am getting an error. My code is below:
using EFCodeFirst
BookDBContext _db = new BookDBContext();
[ChildActionOnly]
public ActionResult GenreMenu()
{
var categories = _db.Category.ToList();//**Giving error at this pointInvalid object name dbo.Categories**
return PartialView(categories);
}

Verify that your BookDBContext contains a property called Category and that your database contains table dbo.Categories.

Related

Getting error when multiple results passing to view in asp.net MVC5

I use asp.net mvc 5 and EF 6 .I have following code in my controller
var resultOne = stats.GetPlayerStatsByParam(year, modeOne); //first
ViewData["more"] = stats.GetTeamStatsID(year); //second
return View("StatsNew", resultOne.ToList());
I am able to display result in view using "resultOne". Now I want to pass another data to same view using ViewData[]. its a stored procedure and the result is paasing to "ViewData["more"]".
I have done following code for "ViewData["more"]" in View page
But I am getting an error saying that 'object reference not set'
#foreach (var item in ViewData["more"] as #List<demo.GetTeamStatsID_Result>)
{
#item.Pld;
}
Use a viewmodel and extend it by the data coming from stats.GetTeamStatsID(year);
Do not use ViewBag or ViewData if not necessary for some reason (which I canĀ“t imagine right now)
As the comments have already pointed out, build a ViewModel class, that wraps everthing you need:
//I am using fake types here, sinceI don't know your model classes
//substitute accordingly!
public class MyViewModel
{
public PlayerStatsType PlayerStats { get; set;}
public List<demo.GetTeamStatsID_Result> Teams { get; set;}
}
Then in your action method:
var vm = new MyViewModel();
vm.PlayerStats = stats.GetPlayerStatsByParam(year, modeOne); //first
vm.TeamId = stats.GetTeamStatsID(year); //second
return View("StatsNew", vm);
Amend the model declaration in your view:
#model Namespace.Models.MyViewModel //again use namespace for your vm class
Now you can access both properties from your model:
#foreach (var item in Model.Teams)
{
#item.Pld;
}

How to query against dbo.AspNetUserLogins table (IdentityUserLogin entity)?

I am using the standard MVC template with the identity provider in VS 2013.
By extending ApplicationUser:IdentityUser, I am able to access the table AspNetUsers using ApplicationDbContext.
I now want to query the data in another table, AspNetUserLogins. How do I reference it without having to create a new database context and a new Entity Data Model to represent this existing table?
The corresponding entity for dbo.AspNetUserLogins table is IdentityUserLogin class. So we just need to declare an appropriate IDbSet<IdentityUserLogin> or DbSet<IdentityUserLogin> property in the ApplicationDbContext class as follows:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
// ...
public IDbSet<IdentityUserLogin> UserLogins { get; set; }
// ...
}
and then query it as usually:
using (var dbContext = new ApplicationDbContext())
{
var userLogins = dbContext.UserLogins.ToList();
}
I know this is old but for anyone looking to do this with asp .Net Core:
Add user manager to your controller constructor that you can access below by DI.
var user = await _userManager.GetUserAsync(User);
var hello = await _userManager.GetLoginsAsync(user);

PUT in MVC Single Page App Template creating new object? Why?

I'm looking at the single-page web application for MVC4 from VS templates (from here http://www.asp.net/single-page-application) and it looks like the PUT action for ToDoLists is creating a new ToDoList - why is this? The code from the DTO class definition:
public TodoList ToEntity()
{
TodoList todo = new TodoList
{
Title = Title,
TodoListId = TodoListId,
UserId = UserId,
Todos = new List<TodoItem>()
};
foreach (TodoItemDto item in Todos)
{
todo.Todos.Add(item.ToEntity());
}
return todo;
}
From the controller:
public HttpResponseMessage PutTodoList(int id, TodoListDto todoListDto)
{
TodoList todoList = todoListDto.ToEntity();
db.Entry(todoList).State = EntityState.Modified;
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
So to update a record, we create a new one? I'm a little confused about how this is working - any clarification would be awesome.
In this example, the controller is converting the TodoListDto object into a TodoList object, which is the database object type. Since the DTO object is coming back from the web page, it has to be changed into the appropriate type so that Entity Framework can attach it to the DbSet and save changes.
ToEntity doesn't actually create a new record in the database, it creates a new TodoList instance which then gets attached, as modified to the database.

Error getting foreign key data on entity

I'm new in MVC2 and Entity Framework and I tried get a list of products with the respective category name, but it's returned me the error
"Object reference not set to an instance of an object."
I have a table Product with a foreign key Category.
I'm using MVC2 and Entity Framework 4.0.
public class Repository
{
public IQueryable<Produto> ListAllProducts()
{
return entities.Produtos;
}
}
public class AdminProdutoController : Controller
{
TudoDeMassinhaRepository repository = new TudoDeMassinhaRepository();
public ActionResult Index()
{
var produtos = repository.ListAllProducts().ToList();
return View(produtos);
}
}
code in view where the error is generated: <%: item.CatProduto.cat_produto_nome%>
You're only selecting the products - you're not currently including the categories. This means: you'll get back your product objects, but any related objects they refer to are not loaded automatically - that's why the .CatProduto property will be NULL and thus you're getting the error.
You need to explicitly specify which additional entities you want to have loaded - something like:
public IQueryable<Produto> ListAllProductsWithCategories()
{
return entities.Produtos.Include("CatProduto");
}
This way, you should get back your Produto objects, and their CatProduto property should have been loaded and populated, too.
So if you change your index method to be:
public ActionResult Index()
{
var produtos = repository.ListAllProductsWithCategories().ToList();
return View(produtos);
}
it should work.

passing variable to view ASP MVC

I have 2 views, one to return all the locations belonging to a project, the other returns a json file containing the locations that used to show them on a google map.
Listing the locations works like this as the id is sent with the actionlink, but how do I send the project ID to the Map view?
public ActionResult GoogleMaps(int id)
{
return View(Project.Find(id).DeviceLocations);
}
//[AutoRefresh(DurationInSeconds = 30)]
public ActionResult Map(int id)
{
var map = Project.Find(id).DeviceLocations;
Locations l = new Locations();
l.locations = map;
return Json(l, JsonRequestBehavior.AllowGet);
}
Some people construct a model (class) specifically to handle all of the values being passed from the controller. So, your model would have a property called DeviceID, and would thus be strongly typed.
Alternately, you can use ViewData:
You can put this in your controller:
ViewData["DeviceID"] = id;
Then, in your view, you will need to cast it before you use it, like this:
(int)ViewData["DeviceID"]
Include a get, set property "project ID" in your Locations class.

Resources