Hi i would like to write a linq query to retrieve all data of a composite table which is generated as a result of many to many relationship.
This is my query in controller
public ActionResult Index()
{
var act = (from i in _context.act
from j in _context.mvz
where i.Id == j.Id
select i).ToList();
var mvz = _context.mvz.ToList();
var vm = new AAMMViewModel()
{
actz = act
mvz = mvz
};
if (vm == null)
{
return Content("No items found in database");
}
return View(vm);
}
This is view model
public class AAMMViewModel
{
public List<Actors> actz { get; set; }
public List<Movies> mvz { get; set; }
public AAMMViewModel()
{
actz = new List<Actors>();
mvz = new List<Movies>();
}
}
It does not gives the desired result, I know that something is wrong with the logic of my Linq query.
Please guide me if anyone has expertise in this regard.
You can do this:
var act =
(from i in _context.act
where i.Id.SelectMany(id => _context.mvz.Contains(id.Id))
select i).ToList();
Are you sure the ids of Actors and Movies are same. If yes, do the join and use the right property name. You are using act in place of actz in your linq
public class AAMMViewModel
{
public List<Actors> actz { get; set; }
public List<Movies> mvz { get; set; }
public AAMMViewModel()
{
actz = new List<Actors>();
mvz = new List<Movies>();
}
}
var act = (from i in _context.actz
join j in _context.mvz ON i.Id == j.Id
select i).ToList();
Related
i'm trying to pass data(.tolist) in inner join query to viewmodel, to use these data in view that contain also a partial view that needs data from viewModel.
public ActionResult IndexAdmin()
{
int userId = (int)Session["UserID"];
userInfo = _context.UserInfo.Find(userId);
var AllTours= (from p in _context.PostsInfo //Why this doesn't return two records
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new
{
RegionName = r.CountryId,
ImageName = p.ImageName,
}).Distinct().ToList();
//Here i need to define IndexAdminViewModel to populate tours and userInfo.username
return View(AllTours);
}
This is the IndexAdminViewModel:
public class IndexAdminViewModel
{
public string UserName { get; set; }
public string RegionName{get;set;}
public string ImageName {get;set;}
}
The view(IndexAdmin.cshtml)
#Html.Partial("_BarPartialAdmin", Model)
foreach (var post in Model)
{
<img src="~/images/#post.ImageName" alt="QfirstImage">
<h2>post.RegionName</h2>
}
The partial view will only needs the username to display it for once so i used to pass the model to partial view in order to use the username property, the RegionName and ImageName is a collection so that i can iterate over them and get teh values some way like use them in a table.
My question is how to pass the inner join query results AND theuserinfo.username to viewModel to use them in the view???????
You need to create 2 view models
public class ToursViewModel
{
public string RegionName { get; set; }
public string ImageName {get; set; }
}
public class IndexAdminViewModel
{
public string UserName { get; set; }
public IEnumerable<ToursViewModel> Tours {get;set;}
}
Then in the controller
public ActionResult IndexAdmin()
{
int userId = (int)Session["UserID"];
userInfo = _context.UserInfo.Find(userId);
IEnumerable<ToursViewModel> tours = (
from p in _context.PostsInfo
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new ToursViewModel
{
RegionName = r.CountryId,
ImageName = p.ImageName
});
IndexAdminViewModel model = new IndexAdminViewModel
{
UserName = userInfo.username,
Tours = tours
};
return View(model);
and in the view
#model IndexAdminViewModel
....
<h1>#Model.UserName</h1>
#foreach (var tour in Model.Tours)
{
<img src="~/images/#tour.ImageName" alt="QfirstImage">
<h2>#tour.RegionName</h2>
}
I you need to pass different objects to the view you basically have two options:
Create a composite class and use that as model
var allTours=
from p in _context.PostsInfo //Why this doesn't return two records
join r in _context.Region
on p.RegionId equals r.Id
where r.CountryId == 1
select new PostAndRegion
{
Region = r.CountryId,
Post= p.ImageName,
};
var model = new MyCompositeModel
{
PostsAndRegions = allTours.ToArray(),
UserInfo = null // or get from where you want to
};
return View(model);
with
public class PostAndRegion
{
public Post Post{get;set;}
public Region Region {get;set;}
}
public class MyCompositeModel
{
public IList<PostAndRegion> PostsAndRegions{get;set;}
public UserInfo MyUserInfo{get;set;}
}
Put some of the data in the ViewBag. see http://www.tutorialsteacher.com/mvc/viewbag-in-asp.net-mvc
I'm trying to send data with a view and print it out, but I'm struggling really hard since I'm very new to C#.
So here's my model ViewModel:
namespace P104.Models
{
public class ViewModel
{
}
public class Location
{
public int loc_id { get; set; }
public string loc_name { get; set; }
}
public class Competentie
{
public int Comp_id { get; set; }
public string competentie { get; set; }
}
public class MyViewModel
{
public User User { get; set; }
public IEnumerable<Locations> Locations { get; set; }
public IEnumerable<Competenties> Competenties { get; set; }
}
}
This is the function I have in the controller
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.user.Find(id);
if (user == null)
{
return HttpNotFound();
}
var competenties =
from usercomp in dbE.UserComp
join comp in dbE.Competenties on usercomp.fk_Comp_id equals comp.comp_id
where usercomp.fk_user_id == id
select new Competenties { competentie = comp.competentie };
var locations =
from userloc in dbE.UserLoc
join loc in dbE.Locations on userloc.fk_location_id equals loc.loc_id
where userloc.fk_user_id == id
select new Locations { loc_name = loc.loc_name };
var model = new MyViewModel
{
User = user,
Locations = locations.ToList(), // eagerly fetch the data that will be needed in the view
Competenties = competenties.ToList(), // eagerly fetch the data that will be needed in the view
};
return View(model);
}
And he's how I try to print it out in the view:
#foreach (var location in Model.Locations)
{
<dt>#location.locname</dt>
<dd>#location.locname</dd>
}
#foreach (var competentie in Model.Competenties)
{
<dt>#competentie.competentie</dt>
<dd>#competentie.competentie</dd>
}
I always recevie this error
The entity or complex type 'P104.Models.Locations' cannot be
constructed in a LINQ to Entities query.
I've found a few solutions, but I'm struggling to apply them to my code so they don't work.
Thanks in advance for your help
You seem to have got a typo here:
select new Locations { loc_name = loc.loc_name };
This should be:
select new Location { loc_name = loc.loc_name };
The model you are projecting against is called Location, not Locations. It's unclear what the Locations model is since you haven't shown that in your question.
And of course adapt your view accordingly:
#foreach (var location in Model.Locations)
{
<dt>#location.loc_name</dt>
<dd>#location.loc_name</dd>
}
By the way I will recommend you following standard C# naming conventions. This convention dictates that in C# a property name should start with an uppercase letter and not contain _. So basically you would rather use LocationName or just Name instead of loc_name. Same remark for your Competentie model.
I am working on ASP.NET-MVC5 applications. I need to pass data model from multiple classes from controller to view so I decided it use ViewModel and use linq to assign values to the view model accordingly. Now I my model, Student can have multiple emergency contact so I am using List but getting error on this part in LINQ query.
ViewModel
public class StudentDetailedProfileViewModel
{
public StudentDetailedProfileViewModel() { }
public Student _studentModel { get; set; }
public Course _courseModel { get; set; }
public School _schoolModel { get; set; }
public Campus _campusModel { get; set; }
public ContactDetail _contactDetailModel { get; set; }
public List<EmergencyContact> _emergencyContactModel { get; set; }
}
Function that need to return strongly typed binded data
public StudentCourseSchoolAndCampusViewModel GetCourseByStudentID(int _studentID)
{
try
{
using (var _uow = new StudentProfile_UnitOfWork())
{
var _record = (from _course in _uow.Course_Repository.GetAll()
join _school in _uow.School_Repository.GetAll() on _course.SchoolID equals _school.SchoolID
join _campus in _uow.Campus_Repository.GetAll() on _course.CampusID equals _campus.CampusID
where _course.StudentID == _studentID
select new StudentCourseSchoolAndCampusViewModel {_courseModel= _course, _schoolModel = _school, _campusModel = _campus }).FirstOrDefault();
return _record;
}
}
catch { return null; }
}
I have managed to do as following but I am not sure if it is the best practice!!
public StudentDetailedProfileViewModel GetStudentDetailedProfileByStudentID(int _studentID)
{
try
{
using (var _uow = new StudentProfile_UnitOfWork())
{
StudentDetailedProfileViewModel StudentProfileObject = new StudentDetailedProfileViewModel();
var _profile = (from _student in _uow.Student_Repository.GetAll()
join _contactDetail in _uow.ContactDetail_Repository.GetAll() on _student.StudentID equals _contactDetail.StudentID
join _studentCourse in _uow.Course_Repository.GetAll() on _student.StudentID equals _studentCourse.StudentID
join _school in _uow.School_Repository.GetAll() on _studentCourse.SchoolID equals _school.SchoolID
join _campus in _uow.Campus_Repository.GetAll() on _studentCourse.CampusID equals _campus.CampusID
where _student.StudentID == _studentID
select new StudentDetailedProfileViewModel { _studentModel = _student, _contactDetailModel = _contactDetail, _courseModel = _studentCourse,_schoolModel = _school, _campusModel = _campus}).FirstOrDefault();
_profile._emergencyContactModel = (from _emergencyContact in _uow.EmergencyContact_Repository.GetAll()
where _emergencyContact.StudentID == _studentID
select _emergencyContact).ToList();
return _profile;
}
}//
catch { return null; }
}
You need to make sure the view model you defined are same as what value you are holding from the Database.
If you hold any List type view model inside a view model, you can manage the return object with the below code
Var getData = new List < ParentViewModel > ();
getData = (from objtbl1 in ParentTable
select new ParentViewModel
{
proty1 = objtbl1 .proty1,
childViewModelProprt = (from objChildtbl1 in childTable
select new ChildViewModel
{
childPrty1 = objChildtbl1.childPrty1
}).toList()
}).toList();
return getData;
Let me know if that helps.
I am working with a action method in which I add a linq query with joins. Now I want to add view for this action method. But the problem is this the linq query is getting data from two entity models and I want to select strongly type view then which class I have to add for this. Here is the Action Method
public ActionResult Marks(int id)
{
var marksjoin = (from a in db.TbStudent
join b in db.TbMarks on a.StudentId equals b.StudentId
select new
{
a.StudentName,
b.StudentId,
b.Hindi,
b.English,
b.SocialStudy,
b.Science,
b.Maths,
b.Total
}).ToList();
// var marks = db.TbMarks.Where(m => m.StudentId == id).SingleOrDefault();
if (marksjoin == null)
{
return RedirectToAction("PostMarks");
}
else
{
return View(marksjoin);
}
Now I am getting the data from two entity models and how can I create a strongly type view for this ?
You need to create a new Type (resulting) and then dump your LINQ output into that Type:-
public class NewType
{
public List<Item> Items1{ get; set; }
public List<Item> Items2{ get; set; }
public string Items3{ get; set; }
............and so on
}
Then pass this 'NewType' as strong type to your view.
Query projection explained
var marksjoin = (from a in db.TbStudent
join b in db.TbMarks on a.StudentId equals b.StudentId
select new StudentType
{
StudentName = b.StudentName,
StudentId = b.StudentId,
// etc
}).ToList();
public class StudentType {
public string StudentName { get; set; }
public int StudentId { get; set; }
// etc...
}
I'm new to MVC5,I had troubles with the problem.
can anybody help me?
I have 2 table, DocMain(Doc_Id,Doc_Title) , DocProduct(Doc_Id,Doc_Content),
I want to select the 2 table content by the same Doc_Id.
And loop them.
Display like:
<ul>
<li>title1content1</li>
<li>title2content2</li>
<li>title3content3</li>
</ul>
....
And how to do it?
//Here is my viewmodel
public class MainProductViewModel
{
public IEnumerable<DocMainListView> DocMainListView { get; set; }
public IEnumerable<DocProductListView> DocProductListView { get; set; }
}
-------------------------------------------------
//Here is my controller
public class DocProductController : Controller
{
private IDocProductRepository repository;
private IDocMainRepository repositoryMain;
public DocProductController(IDocProductRepository docProductRepository, IDocMainRepository docMainRepository)
{
this.repository = docProductRepository;
this.repositoryMain = docMainRepository;
}
public ActionResult List()
{
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new { DocMainTitle = docMain.Doc_Title, DocProductContent = docProduct.DocProduct_Content };
//ViewBag.products = products;
//DocProductListView model = new DocProductListView
//{
// DocProduct = repository.DocProduct
// .Join(repositoryMain.DocMain,
// docProduct => docProduct.Doc_Id,
// docMain => docMain.Doc_Id,
// (docProduct, docMain) => new { a = docMain.Doc_Id, b = docProduct.Doc_Id })
// .OrderByDescending(n => n.)
//};
return View(products);
}
}
I don't know how to write the controller code and View code.
As you want to display the title and content only, so your view model would be
public class MainProductViewModel
{
public IEnumerable<ProductInfo> Products { get; set;}
}
public class ProductInfo
{
public string DocMainTitle { get; set;}
public string DocProductContent { get; set;}
}
And your query would be:
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new ProductInfo { DocMainTitle = docMain.Doc_Title, DocProductContent =
docProduct.DocProduct_Content };
And assign this products to the Products of MainProductViewModel and return to view, then config your view as
#model MainProductViewModel