I got this in the controller
var tobi = (from a in db.Assessments
join u in db.Users on a.rated equals u.user_id
join tm in db.Team_Members on u.user_id equals tm.user_id
join t in db.Teams on tm.team_id equals t.team_id
where (tm.end_date == null || tm.end_date > DateTime.Today)
group new TobiViewModel
{
teamname = t.name,
assessed_due = a.assessed_due,
assessment_id = a.assessment_id,
rater = a.rater,
rated = a.rated
}
by new { t.name, a.rated }).ToList();
return View(tobi);
But then it doesn't accept it in the view?
The model item passed into the dictionary is of type
'System.Collections.Generic.List1[System.Linq.IGrouping2[<>f__AnonymousType102[System.String,System.String],Kyubu.ViewModels.TobiViewModel]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable1[Kyubu.ViewModels.TobiViewModel]'.
how should i pass this in the view. Any help would be appreciated
The type in the view is
#model IEnumerable<Kyubu.ViewModels.TobiViewModel>
Try the following in the view:
#model IEnumerable<System.Linq.IGrouping<object, Kyubu.ViewModels.TobiViewModel>>
Related
I'm trying to fetch the record from 3 tables by comparing the user Logged in name
Here is my code:
public ActionResult MeritList() //departmental merit listed students details with status 1
{
var username= HttpContext.Session["UserName"];
List<StdListModel> model = new List<StdListModel>();
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
//join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && e.tblDepartment.DepartName == username
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
foreach(var item in query)
{
model.Add(new StdListModel()
{
ID=item.ID,
Name=item.Name,
FatherName=item.FatherName,
CNIC=item.CNIC,
FormNo=item.FormNo,
DiaryNo=item.DiaryNo
});
}
return View(model);
}
Also Tried this Query
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && d.DepartName.Equals(username)
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
But it does not return anything model=0, query =0, the database has right values and I don't get any error either.
please check username with tolower() and trim function.
e.tblDepartment.DepartName.ToLower().Trim() == username.ToLower().Trim()
or
e.tblDepartment.DepartName.ToLower().Trim().equals(username.ToLower().Trim())
I got the problem. It is in
s.Status == '1'
I just changed it into
s.Status == 1
and it works fetch the data from the database.
I want to return multiple column in join result and fill in view model(VMFoodFoodMeal).
for example I want to fill VMFoodFoodMeal by Join result
Thanks
IEnumerable<VMFoodFoodMeal> _fmt = (from e in db.FoodProgramMealFood
join j in db.Foods on e.FoodId equals j.Id
select new
{
Id = e.Id,
Name = j.Name,
});
It is hard to understand what you want, but as example you can look here at Group Join section.
Here is an example code from there:
public void Linq103()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category into ps
select new { Category = c, Products = ps };
foreach (var v in q)
{
Console.WriteLine(v.Category + ":");
foreach (var p in v.Products)
{
Console.WriteLine(" " + p.ProductName);
}
}
}
result:
Beverages:
Chai
Chang
Guaraná Fantástica
Sasquatch Ale
Steeleye Stout
Côte de Blaye
Chartreuse verte
Ipoh Coffee
...
if you want to send your join Result to a model without using foreach statement you have to use this code
IEnumerable<VMFoodFoodMeal> _fmt = (from e in db.FoodProgramMealFood
join j in db.Foods on e.FoodId equals j.Id
select new VMFoodFoodMeal()
{
Id = e.Id,
Name = j.Name,
});
for example in above code I had a view model (VMFoodFoodMeal) and want to fill it by join result.
I have to make new instance of my model in select and then fill its property.
Thanks
I have a LINQ to Entities Query that is suppose to return a specific resultset based on the GUID provided.
[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json)]
public List<OrderDetails> GetOrderDetailsByGUID(Guid OrderID)
{
var listit =(from OV in EC.OrderProductVariants
join O in EC.Orders on OV.OrderId equals O.Id
join PV in EC.ProductVariants on OV.ProductVariantId equals PV.Id
join P in EC.Products on PV.ProductId equals P.Id
join CT in EC.Customers on O.CustomerId equals CT.Id
join AD in EC.Addresses on CT.BillingAddress_Id equals AD.Id
where O.OrderGuid == OrderID
select new OrderDetails
{
OrderID = O.OrderGuid,
Company = AD.Company,
ShippingMethod = O.ShippingMethod,
Product = P.Name,
QuantityOnOrder = OV.Quantity
}
).ToList();
return listit;
}
It Returns NULL, can anyone tell me what I am doing wrong?
All solution that could work in a scenario like this is to create a view and do just a one liner code to access it
var q = EC.OrderProductVariants.SingleOrDefault(u => u.OrderGuid.Equals(guid));
List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = c.Date.ToString(), Data = c.Comment }
).ToList();
The code above causes exception on the convertion of date to string, PostingDate = c.Date.ToString(). Any ideas how to get around this?
Exception error:
{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
linq is trying to convert date to string using sql but since there is no ToString() method in sql it can't convert it, this behavior is by design - Joakim
In other words, return the date itself and convert it to a string after it executes on SQL side:
(
select new { Username = u.Username,
PostingDate = c.Date
[...]
})
.ToList() // runs on SQL and returns to the application
.Select(o => // is not generating a SQL, it is running on the app
new Post { Username = o.Username,
PostingDate = o.PostingDate.ToString(),
[...]
})
You can remedy your problem by projecting into an anonymous type, and then at a later step project into Post after the data has already been returned from the DB.
(from ....
select new { /* stuff */, Date = c.Date })
.AsEnumerable()
.Select(p => new Post { /* stuff */, PostingDate = p.Date.ToString() })
.ToList();
However, given that you have a property called PostingDate, the original source being a date, I would recommend your revise your object to actually keep the value as a DateTime instead of a string.
I dont think this can be done in a direct way.
var list =
select new Post { Username = u.Username, PostingDate = SqlFunctions.StringConvert(c.Date), Data = c.Comment }
from
(from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending).AsEnumerable()
).ToList();
Also with EF4 you can try something like this:
List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = SqlFunctions.DateName(c.Date), Data = c.Comment }
).ToList();
Hi guys i need to replicate this SQL query in Linq to Entity
select * from Subscriber a
inner join User b on a.UserId = b.Id
where b.Username = 'Name'
May be some one may help.
Try this:
var query = from s in context.Subscribers.Include("User")
where s.User.Username == "Name"
select s;
This suppose that Subscriber has navigation property User referencing the user instance.
If you wan to use join (which is not needed) you can use this for inner join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id
where u.Username == "Name"
select new
{
Subscriber = s,
User = u
};
or this for left outer join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id into x
where u.Username == "Name"
from y in x.DefaultIfEmpty()
select new
{
Subscriber = s
User = y,
};