how to display data from both two tables in database in a View in mvc4 razor - sql-server

Can anybody guide me how to display data from two tables in database in view page of MVC4 using razor?i googled it but i didnt find answer for this
LeadDetail.cs
public partial class LeadDetail
{
public int LeadID { get; set; }
public string LeadName { get; set; }
public virtual logintable logintable { get; set; }
}
EmployeDetail.cs
public partial class EmployeDetail
{
public int EmployeID { get; set; }
public int UserID { get; set; }
public string EmployeeName { get; set; }
public virtual logintable logintable { get; set; }
}
Parentview.cs in viewmodels folder
public class Parentview
{
public List<LeadDetail> LeadDetails { get; set; }
public List<EmployeDetail> EmployeDetails { get; set; }
public ParentsInformationViewModel(List<LeadDetail> _LeadDetails, List<EmployeDetail> _EmployeDetails) //Should i pass all the required parameters that i want to display in view ????
{
LeadDetails = _LeadDetails;
EmployeDetails = _EmployeDetails;
}
Homecontroller.cs
public ActionResult view()
{
List<LeadDetail> LeadObj = new List<LeadDetail> ();
List<EmployeDetail> EmployeObj = new List<EmployeDetail> ();
// get list of parents here
Parentview ParentInfoVMObj = new Parentview();
ParentInfoVMObj.LeadDetails = LeadObj;
ParentInfoVMObj.EmployeDetails = EmployeObj;
return View(ParentInfoVMObj);
}

see below sample
First Table
public class Table1
{
public int Id{ get; set; }
public string Name{ get; set; }
}
Second Table
public class Table2
{
public int Id{ get; set; }
public string Name{ get; set; }
}
ViewModel
public class ViewModelForTwoTables
{
public List<Table1> table1Data { get; set; }
public List<Table2> table2Data { get; set; }
}

see below example
public ActionResult TeamStat()
{
var players = db.Players().ToList();
var seasons = db.Seasons().ToList();
var view = new TeamStat()
{
Players = players,
Seasons = seasons
};
return View(view);
}
in view
#foreach (var player in Model.Players) { ....
#foreach (var player in Model.Seasons) { ....

Related

EF core order by navigation property

I have an entity relationship like this.
public class Provider
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<ProviderPod> ProviderPods { get; set; } = new List<ProviderPod>();
}
public class ProviderPod
{
public int Id { get; set; }
public int ProviderId { get; set; }
public int PodId { get; set; }
public virtual Provider Provider { get; set; }
public virtual Pod Pod { get; set; }
}
public class Pod
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProviderPod> ProviderPods { get; set; } = new List<ProviderPod>();
}
I need to order the 'Provider' entity by it's navigation property ProviderPods' "Name" separated by a comma. Something like this
IQueryable<Provider> entityQuery = context.Providers.AsQueryable();
//Need to enter Appropriate query below
entityQuery = entityQuery.OrderByDescending(x => string.Join(", ", x.ProviderPods.Select(y => y.Pod.Name)));
var list = entityQuery.Take(12).ToList();
What would be the best way to achieve this ordering?

How to get all data from ef core many to many

On EF core have Two tables(Page, Group) both have many to many relations with junction table GroupPage. Want to get all pages data with junction table related data based on groupId as like bellow.
If you construct your EF relation correctly you should not have a GroupPage entity.
See Entity Framework Database First many-to-many on how to construct your EF EDM correctly.
Once you have your EDM correctly mapped, you should have the classes
public class Page
{
public int Id { get; set; }
public ICollection<Group> Groups { get; set; }
...
}
public class Group
{
public int Id { get; set; }
public ICollection<Page> Pages { get; set; }
...
}
Then you just need to do the following
public IQueryable<Page> GetPages(int groupId)
{
return from group in _context.Groups
where group.Id == groupId
from page in group.Pages
select page;
}
The following syntax is self-descriptive. Here are the entities structure and Page Dto.
public class Page
{
public int Id { get; set; }
public ICollection<Group> Groups { get; set; }
...
}
public class Group
{
public int Id { get; set; }
public ICollection<Page> Pages { get; set; }
...
}
public class PageGroup
{
public int PageId { get; set; }
public Page Page { get; set; }
public int GroupId { get; set; }
public Group Group { get; set; }
}
public class PagesDto
{
public string Name { get; set; }
public int GroupId { get; set; }
public int PageId { get; set; }
public string Description { get; set; }
public string Tab { get; set; }
public string Module { get; set; }
public bool? IsActive { get; set; }
public bool? IsDefault { get; set; }
public PagesDto()
{
IsActive = false;
IsDefault = false;
}
}
Following function help us to get group related pages information.
public async Task<List<PagesDto>> GetAllPagesByGroupId(int selectedGroupId)
{
//get all pages
var pages = await _pagesRepository.GetAll().Select(p => new PagesDto {
PageId = p.Id,
Name = p.Name,
GroupId = 0
}).ToListAsync();
//get group ralated pages
var selectedGroupPageIds = _groupPagesRepository
.GetAll()
.Where(p => p.GroupId == selectedGroupId)
.Select(p => p.PageId);
//update page information base on group related pages info.
foreach (var item in pages.Where(p=>selectedGroupPageIds.Contains(p.PageId)))
{
item.GroupId = selectedGroupId;
}
return pages;
}

How to access foreign key values on MVC view?

I'm having trouble accessing foreign key values in my view without using a partial.
I have tblProperty as Primary_Key and tblCustomer as foreign_key. I want to access the values of my foreign keys in my view but can't figure out why.
Model
public partial class tblProperty
{
public tblProperty()
{
this.Images = new HashSet<Image>();
this.tblCustomers = new HashSet<tblCustomer>();
}
public int propertyID { get; set; }
public string address { get; set; }
public string description { get; set; }
public virtual ICollection<Image> Images { get; set; }
public virtual ICollection<tblCustomer> tblCustomers { get; set; }
}
public partial class tblCustomer
{
public int customerID { get; set; }
public string name { get; set; }
public decimal contactNumber { get; set; }
public string notes { get; set; }
public Nullable<int> propertyID { get; set; }
public virtual tblProperty tblProperty { get; set; }
}
controller
public class propertyController : Controller
{
propertyDBEntities2 dc = new propertyDBEntities2();
public ActionResult List()
{
var properties = dc.tblProperties.Include(p => p.tblCustomers);
return View(properties.ToList());
}
public ActionResult Details(int id = 0)
{
var properties = dc.tblProperties.Include(p => p.tblCustomers);
tblProperty property = dc.tblProperties.Find(id);
tblCustomer customer = dc.tblCustomers.Find(id);
if (properties == null)
{
return HttpNotFound();
}
return View(dc.tblProperties.Find(id));
}
public ActionResult Create()
{
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(tblProperty e)
{
if (ModelState.IsValid)
{
using (dc)
{
dc.tblProperties.Add(e);
dc.SaveChanges();
}
}
return RedirectToAction("List");
}
view
(like model.name is trying to access name from tblCustomer)
#model myProject.tblProperty
#Html.DisplayFor(model => model.name)
tblProperty doesnt have name.
I guess you need
#Html.DisplayFor(model => model.tblCustomer.name)
But just debug it or use intellisense
EDIT:
In my project I create a dtoClass Data Transfer Object
So for my avl class I have a dtoAvl
avl Class:
public partial class avl
{
public avl()
{
this.cars = new HashSet<cars>();
}
public long avl_id { get; set; }
public Nullable<long> car_id { get; set; }
public Nullable<decimal> speed { get; set; }
// this class contain info regarding the road
public virtual manila_rto manila_rto { get; set; }
public virtual ICollection<cars> cars { get; set; }
}
I create a dtoAvl
public class dtoAvl
{
public long Avl_ID { get; set; }
public long? Car_ID { get; set; }
public string RoadName { get; set; } // came from manila_rto
public int Speed { get; set; }
}
My controler
List<dtoAvl> result = db.avls.Select(
r => new dtoAvl
{
Avl_ID = r.Avl_ID,
Car_ID = r.Car_ID,
Speed = r.Speed,
// here is a propery but can be a list
RoadName = r.manila_rto.name
}).ToList();
return PartialView(result);
View:
#model IEnumerable<dtoAvl>

Breeze saving strategy

I'm creating my first spa with angular and breeze. So for so good and i'm very happy with the progress I've made. But now I'm stuck on my editing and saving my entity product (example class below). When I edit a product i also call the related products, and I have a checkbox (on saving) that says "override related products with same info". But what is the best way to do this? Server side? Should i expand the model on the client side? Are there examples available?
Product:
public class Product
{
#region Fields
private ICollection<ProductCategory> _productCategories;
private ICollection<ProductManufacturer> _productManufacturers;
private ICollection<ProductPicture> _productPictures;
private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;
private ICollection<ProductTierPrice> _productTierPrices;
#endregion Fields
#region Properties
public int Id { get; set; }
public ProductType ProductType { get; set; }
public int ParentGroupedProductId { get; set; }
public bool VisibleIndividually { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public string UniqueCode { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTime? SpecialPriceStartDateTimeUtc { get; set; }
public DateTime? SpecialPriceEndDateTimeUtc { get; set; }
public decimal DiscountPercentage { get; set; }
public bool HasTierPrices { get; set; }
public TaxRate TaxRate { get; set; }
public bool SyncToShop { get; set; }
public bool Deleted { get; set; }
public bool Locked { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
#endregion Properties
#region Mapping
public virtual ICollection<ProductCategory> ProductCategories
{
get { return _productCategories ?? (_productCategories = new List<ProductCategory>()); }
protected set { _productCategories = value; }
}
public virtual ICollection<ProductManufacturer> ProductManufacturers
{
get { return _productManufacturers ?? (_productManufacturers = new List<ProductManufacturer>()); }
protected set { _productManufacturers = value; }
}
public virtual ICollection<ProductPicture> ProductPictures
{
get { return _productPictures ?? (_productPictures = new List<ProductPicture>()); }
protected set { _productPictures = value; }
}
public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
{
get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
protected set { _productSpecificationAttributes = value; }
}
public virtual ICollection<ProductTierPrice> ProductTierPrices
{
get { return _productTierPrices ?? (_productTierPrices = new List<ProductTierPrice>()); }
protected set { _productTierPrices = value; }
}
#endregion Mapping
}
Related Product:
public class RelatedProduct
{
#region Fields
#endregion Fields
#region Properties
public int Id { get; set; }
public int ProductId1 { get; set; }
public int ProductId2 { get; set; }
public int DisplayOrder { get; set; }
public State State { get; set; }
#endregion Properties
//#region Mapping
//public virtual Product Product1 { get; set; }
//public virtual Product Product2 { get; set; }
//#endregion Mapping
}
Capture Changes of All Products in Clinent Jquery Array and send to Server Side..
Serverside change your controller method argument to IEnumerable products , so you can save all changes in Batch
If you want to update only change value use HttpPatch on server side and update changed value only

Classes and relationship design in mvc 3.0

I have currently have the following classes:
public class Ticket
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
public virtual ICollection<Item> Items { get; set; }
public Ticket()
{
Items = new List<Item>();
}
}
public class Client
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
public class Item
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public double Price { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
My Problem/Question is the following, let's say I create a new Item: "Item1" and set its price to "3.00", I add that Item to a few "Tickets", i.e., "Ticket1": "Item1", "3.00"; "Ticket2": "Item1", "3.00", etc. If after adding these items to the tickets I change "Item1"'s price to "4.00" it would change the price of the ticket I already created, how can I have it change the price for only ticket created after the price change?
This is my ticket controller:
[HttpPost]
public ActionResult Create(TicketViewModel ticketViewModel)
{
if (ModelState.IsValid)
{
var ticket = new Ticket();
ticket = ticketViewModel.Ticket;
AddOrUpdateItems(ticket, ticketViewModel.Item);
context.Tickets.Add(ticket);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(ticketViewModel);
}
private void AddOrUpdateItems(Ticket ticket, ICollection<AssignedItem> assignedItems)
{
foreach (var assignedItem in assignedItems)
{
if (assignedItem.Assigned)
{
var item = context.Items.Find(assignedItem.ItemId);
ticket.Items.Add(item);
}
}
}

Resources