DB Context - Query to select post from a category - asp.net-mvc

I am using DB context approach in my asp.net mvc 4 test project.
Here are my domain classes
Category.cs
public class Categroy
{
public virtual int Id { get; set; }
public virtual string CategoryName{ get; set; }
public virtual ICollection<Post> Post{ get; set; }
}
Post.cs
public class Post
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
}
IPostsDateSource.cs
public interface IPostsDataSource
{
IQueryable<Category> Categories{ get; }
IQueryable<Post> Posts { get; }
void Save();
}
PostsDB.cs
public class PostsDB:DbContext,IPostsDataSource
{
public PostsDB():base("DefaultConnection")
{
}
public DbSet<Category> Categories{ get; set; }
public DbSet<Post> Posts{ get; set; }
void IPostsDataSource.Save()
{
SaveChanges();
}
IQueryable<Category> IPostsDataSource.Categories
{
get { return Categories; }
}
IQueryable<Post> IPostsDataSource.Posts
{
get { return Posts; }
}
}
I am using StructureMap for mapping
IoC.cs
...
x.For<IPostsDataSource>().HttpContextScoped().Use<PostsDB>();
...
In my HomeController I am
private IPostDataSource _db;
public HomeController(IAdsDataSource db)
{
_db = db;
}
I can retrieve all the posts by _db.Posts
public ActionResult Index()
{
var Posts= _db.Posts;
ViewBag.Posts = Posts;
return View();
}
The problem is what query should I write in order to retrieve all posts from a specific categrory

If a category has a collection of Posts, then Post entity should have a CategoryID property. You can query base on that CategoryID.
Otherwise you can query the category and retrieve the corresponding list of Posts:
var cat = _db.Categories.Where(a => a.Id == catId).FirstOrDefault();
if(cat != null)
ViewBag.Posts = cat.Posts;
return View();

Related

Display product and related images in the view, using repository pattern mvc 5

I am trying to create a view to display product information and its related images. I am using repository pattern,
please see the code below, I will really appreciate your help
public class ProductDetail
{
public int pro_id { get; set; }
public string pro_name { get; set; }
public string pro_model { get; set; }
public string pro_Dimensions { get; set; }
public string pro_imageTitle { get; set; }
public string pro_image { get; set; }
public string pro_desc { get; set; }
public Nullable<double> pro_price { get; set; }
public int pro_UnitsInStock { get; set; }
public Nullable<double> pro_oldprice { get; set; }
public virtual ICollection<Images> tbl_Images { get; set; }
}
public class Images
{
public int ImageID { get; set; }
public int productID { get; set; }
public string ImageTitle { get; set; }
public string ImagePath { get; set; }
}
public class ProductDetailRepository : IProductDetail
{
private readonly WebStoreEntities storeDB;
public ProductDetailRepository() { }
public ProductDetailRepository(WebStoreEntities _storeDB)
{
this.storeDB = _storeDB;
}
public ProductDetail GetProductByID(int id)
{
var prod = storeDB.tbl_Product
.Where(x => x.pro_id == id)
.Include(p => p.tbl_Images)
.FirstOrDefault();
return prod; (Here it says, cannot implicitly convert type tbl_product to productdetail (this is where i need help))
}
tbl_product is from the EDMX model.
}
now, i am stcuk in this method, all i want is to return the product info and related images to the controller and then view.
You basically just need to convert your tbl_Product that you get from the database into the ProductDetail you want to return:
public ProductDetail GetProductByID(int id)
{
var prod = storeDB.tbl_Product
.Where(x => x.pro_id == id)
.Include(p => p.tbl_Images)
.FirstOrDefault();
if (prod == null)
{
return null;
}
ProductDetail result = new ProductDetail
{
// I'm just *GUESSING* here since you haven't showed
// the tbl_product class, so I don't know what the
// properties on that class are called, really...
pro_id = prod.Id,
pro_name = prod.Name
// and so on for all the properties
}
return result;
}

how to resolve web api error 'System.OutOfMemoryException'

I am creating ASP.Net MVC WebApi to share my data to bank. In this regard i have created an SQL View bit when i am testing my WebApi it is giving an 'System.OutOfMemoryException' error because i have more the 1 million record in SQL View.
My Code is given below:-
This is my controller
public class InvoiceController : ApiController
{
public IEnumerable<VBank_invoice> Get()
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.ToList();
}
}
public VBank_invoice Get(string consumer)
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.FirstOrDefault(e => e.consumer_no == consumer);
}
}
}
My SQL View Class
public partial class VBank_invoice
{
public int sno { get; set; }
public string consumer_no { get; set; }
public string consumer_name { get; set; }
public string consumer_address { get; set; }
public string billing_month { get; set; }
public Nullable<decimal> current_Charges { get; set; }
public Nullable<decimal> outstanding_Arrears { get; set; }
public Nullable<decimal> Arrears_15 { get; set; }
public Nullable<decimal> part_payment_arrears { get; set; }
public string billing_period_code { get; set; }
public string consumer_checkdigit { get; set; }
public Nullable<System.DateTime> due_date { get; set; }
}
This is my Model.Context.cs File
public partial class kmcEntities : DbContext
{
public kmcEntities()
: base("name=kmcEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<VBank_invoice> VBank_invoice { get; set; }
}
I believe you need to be serialize object model using the select query.
public class InvoiceController : ApiController
{
public IEnumerable<VBank_invoice> Get()
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.select(m => new {
m.sno, m.consumer_no,m.consumer_name, m.consumer_address,
m.billing_month, m.current_Charges, m.outstanding_Arrears,
m.Arrears_15, m.part_payment_arrears, m.billing_period_code,
m.consumer_checkdigit, m.due_date }).ToList();
}
}
}

How to create own/custom controller in Codefirst approach in entity framework

I am trying to make a sample application using code first approach in MVC so I don't have any database. Now I have setup all class files and context class. In next step I have created a controller(Emplty) and want to create own Create/List/Delete functionalities. How can I do it.
Some of the codes are below
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int DepartmentID { get; set; }//Foreign Key
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class EmployeeDBContext: DbContext
{
public EmployeeDBContext()
: base("EmployeeDBContext")//EmployeeDBContext will be name of database.
{ }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Department> Departments { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
}
public class EmployeeInitializer:DropCreateDatabaseIfModelChanges<EmployeeDBContext>
{
protected override void Seed(EmployeeDBContext context)
{
var employee = new List<Employee>
{
new Employee{EmployeeID=1, Name="Aman", Age=15, DepartmentID=11},
new Employee {EmployeeID=2, Name="Supriya", Age=12, DepartmentID=22},
new Employee {EmployeeID=3, Name="Rishabh", Age=10, DepartmentID=44}
};
employee.ForEach(x => context.Employees.Add(x));
context.SaveChanges();
var department = new List<Department> {
new Department{DepartmentID=11, DepartmentName="IT"},
new Department{DepartmentID=22, DepartmentName="HR"},
new Department{DepartmentID=33, DepartmentName="Mechanical"},
new Department{DepartmentID=44, DepartmentName="NGO"}
};
department.ForEach(x=>context.Departments.Add(x));
context.SaveChanges();
var enrollment = new List<Enrollment>() {
new Enrollment{EnrollmentID=111, EmployeeID=1, DepartmentID=11},
new Enrollment{EnrollmentID=222, EmployeeID=3, DepartmentID=44},
new Enrollment{EnrollmentID=333, EmployeeID=2, DepartmentID=22}
};
enrollment.ForEach(x=>context.Enrollments.Add(x));
context.SaveChanges();
}
}
I wish to add code from below controller onward
public ActionResult CreateEmployee(Employee employee)
{
//my desired code here
return View();
}
[HttpGet]
public ActionResult ListEmployee()
{
//my desired code here
return View();
}
you mean how to do something like:
[HttpGet]
public ActionResult ListEmployee()
{
//my desired code here
using(var context=new EmployeeDBContext())
{
return View(context. Employee.ToList());
}
}
[HttpPost]
[Route("api/Employee/CreateEmployee")]
public ActionResult CreateEmployee([FromBody]Employee employee)
{
//add to ef
_db.Add(employee);
_db.SaveChanges();
//my desired code here
return Ok();
}

ApplicationDbContext.EntityName() returning null

Why db.Countries() comes null in following scenario-
1. CityController
[Authorize]
public class CityController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext("CP");
// GET: City/Create
public ActionResult Create()
{
ViewBag.CountryId = new SelectList(db.Countries.ToList(), "CountryId", "Name");
return View();
}
ApplicationDbContext
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
internal IDbSet<Country> Countries { get; set; }
...
}
Country is defined as-
[Table("Country")]
public class Country
{
#region Fields
private ICollection<City> _cities;
#endregion
#region Scalar Properties
public Guid CountryId { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
#endregion
#region Navigation Properties
public virtual ICollection<City> Cities
{
get { return _cities ?? (_cities = new List<City>()); }
set { _cities = value; }
}
#endregion
}
City is defined as-
[Table("City")]
public class City
{
#region Fields
private ICollection<Location> _locations;
#endregion
#region Scalar Properties
public Guid CityId { get; set; }
public Guid CountryId { get; set; }
public string Name { get; set; }
public string CityCode { get; set; }
public string ZipCode { get; set; }
public Country Country { get; set; }
#endregion
#region Navigation Properties
public virtual ICollection<Location> Locations
{
get { return _locations ?? (_locations = new List<Location>()); }
set { _locations = value; }
}
#endregion
}
What could be the reason for not populating Country table records and returning countries to null?
After sparing few hours, I just noticed the Access-modifier of Countries properties which was internal. I made it Public and magic happened! It works though I don't have any explanation on WHY part of it.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
//internal IDbSet<Country> Countries { get; set; }
public IDbSet<Country> Countries { get; set; }
public IDbSet<City> Cities { get; set; }
Thanks everyone.

EF5 ASP.NET MVC 4 Linq query not returning anything & model property null -> Code First

Im having trouble linking my loaned items to my Library for each customer. It does it fine when it goes through the "AddToLibrary" method but when it comes to retreiving it, the medialibrary is empty and the query in the IEnumerable<Item> ItemsOnLoan method is returning null. This is a very basic ASP.NET MVC 4 application and im very new to this so its probably something silly ive missed out.
I just want to be able to add an item to the loaned items table, have the list of loaned items for each customer appear in their personal Library (defined in model) and then retreive the list of their items. Below is all the code and I am using a code first approach. Thank you :)
Model
public class Customer
{
public int Id { get; set; }
public string ForeName { get; set; }
public string SurName { get; set; }
public Address address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public List<LoanedItem> Library { get; set; }
public Customer()
{
if (Library == null || Library.Count == 0)
{
Library = new List<LoanedItem>();
}
}
public IEnumerable<Item> ItemsOnLoan
{
get
{
var items = (from i in Library
where i.Customer.Id == this.Id
select i).OfType<item>();
return items;
}
}
}
Loaned Item model
public class LoanedItem
{
public int? Id { get; set; }
public Customer Customer { get; set; }
public MediaItem Item { get; set; }
}
ItemController --> adding to library method
public ActionResult AddToLibrary(int id)
{
Item libraryItem = db.Items.Find(id);
Customer c = db.Customers.Find(1);
LoanedItem newLoanGame = new LoanedItem()
{
Customer = c,
Item = libraryItem
};
db.LoanedItems.Add(newLoanGame);
db.SaveChanges();
return RedirectToAction("Index");
}
Customer Controller
public ActionResult ViewProfile(int id = 1)
{
Customer c = db.Customers.Find(id);
if (c == null)
{
return HttpNotFound();
}
return View(c);
}
public ActionResult GetLibraryItems(int id = 1)
{
var items = db.Customers.Find(id).ItemsOnLoan;
return View(items);
}
Context
public class LibraryContext : DbContext
{
public DbSet<Address> Addresses { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<LoanedItem> LoanedItems { get; set; }
public DbSet<Item> Items { get; set; }
public LibraryContext()
: base("LbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CustomerConfiguration());
modelBuilder.Configurations.Add(new LoanedItemConfiguration());
modelBuilder.Entity<Item>();
modelBuilder.Entity<Address>();
base.OnModelCreating(modelBuilder);
}
}
Assuming that Proxy generation is enabled try this:
public class Customer
{
public int Id { get; set; }
public string ForeName { get; set; }
public string SurName { get; set; }
public Address address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public virtual ICollection<LoanedItem> ItemsOnLoan { get; set; }
public Customer()
{
}
}
using this to acccess:
public ActionResult GetLibraryItems(int id = 1)
{
var customer = db.Customers.Find(id);
if (customer != null)
{
var items = customer.ItemsOnLoan;
return View(items);
}
//handle not found or throw an exception
throw new Exception();
}
follow this link for more information on Proxies and Lazy Loading.

Resources