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.
Related
I am not much familiar with EF. I want to group rows based on IDs. I acheive this in SQL but I am getting some Issues with group by while implementeing in EF.
public ActionResult PropertyListing()
{
if (Session["UserID"] == null)
{
return RedirectToAction("Login", "Property");
}
return View();
}
public JsonResult GetSpurts()
{
PropertySpurts property;
List<PropertySpurts> listProperty = new List<PropertySpurts>();
var userID = Convert.ToInt32(Session["UserID"].ToString());
// IEnumerable<tblPropertyView> PropertyList;
var PropertyList = from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.PropertyID into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t => t.ID != null) };
if (PropertyList != null)
{
foreach (var item in PropertyList)
{
property = new PropertySpurts();
property.ID = (int)item.ParentId;
property.Title = item.tblProperty.Title;
listProperty.Add(property);
}
}
return Json(listProperty, JsonRequestBehavior.AllowGet);
}
PropertyID in tblPropertyView is Foreign Key to tblProperty ID. I want to get title of Property from tblProperty. Please help me to find Title and Count of PropertyViews
TIA
[SOLVED]
var PropertyList = from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by new
{
p.PropertyID,
p.tblProperty.Title
} into grouped
select new
{
ParentId = grouped.Key.PropertyID,
Title = grouped.Key.Title,
Count = grouped.Count(t => t.ID != null)
};
This solves my issue. But I want this should be orderby count.
var PropertyList = (from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by new
{
p.PropertyID,
p.tblProperty.Title
} into grouped
select new
{
ParentId = grouped.Key.PropertyID,
Title = grouped.Key.Title,
Count = grouped.Count(t => t.ID != null)
}).OrderByDescending(x => x.Count);
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));
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>>
I want to write if condition inside where clause. because if first name or last name is null I don't wani to add it in where clause . other wise I want to add it.
so I write
var query1 = from opv in _opvRepository.Table
join o in _orderRepository.Table on opv.OrderId equals o.Id
join gr in _graduandRepository.Table on opv.graduand_id equals gr.graduand_id
join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
join p in _productRepository.Table on pv.ProductId equals p.Id
where (opv.ceremony_id == ceremony_id) &&
(!o.Deleted) && (opv.IsHireItem == true) &&
(!p.Deleted) &&
(!pv.Deleted) && (opv.ceremony_id == ceremony_id)
// group opv by opv.OrderId into g
select new
{
opvTable = opv,
grTable = gr,
};
// This is not working. I have problem in here. How to add this??
if (!String.IsNullOrEmpty(Fname))
query1 = query1.Where(grTable = > grTable.first_name == Fname);
var result = query1.ToList().Select(x =>
{
return new HireItemReportLine()
{
OrderId = x.opvTable.OrderId,
OrderDate=x.opvTable.Order.CreatedOnUtc,
Amount= x.opvTable.Order.OrderSubtotalExclTax,
PaymentMethod = x.opvTable.Order.PaymentMethodSystemName,
paidDate = x.opvTable.Order.CreatedOnUtc,
Fname = x.grTable.first_name,
MName = x.grTable.middle_name,
LName = x.grTable.last_name,
};
}).ToList();
What is the wrong with my cording??
Note that your original query selects an anonymous type with two properties: opvTable and grTable. So, you need to use one of those properties in the subsequent Where clause, like this:
query1 = query1.Where(item => item.grTable.first_name == Fname);
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();