Linq - Retrieve a single value in a String - c#

I use Asp.net 3.5 and EF 4.
I need find a specific row in my DataBase and display on a label a single value as string.
At the moment I use this code, it is working, so I find a single Object and read its properties.
var myAuthor = (from at in context.CmsAuthors
where at.AuthorId == myRow.AuthorId
select at).Single();
myAuthorNameLabel.Text = myAuthor.LastName;
I would like to know:
If there is another syntax in Linq to achieve the same result.
How to do it using Lamba?
Which approach would you suggest me?

Here's the method syntax (using lambdas)
myAuthorNameLabel.Text = context.CmsAuthors
.Where(at => at.AuthorId == myRow.AuthorId)
.Select(at => at.LastName)
.SingleOrDefault() ?? string.Empty;

You can use:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Single().Select(a => a.LastName);
actually this would be even better:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select(a => a.LastName).Single();
Update
An example of how to use with Anonymous type:
var myAuthorNames =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select( a => new {a.LastName, a.FirstName}).Single();

Related

Convert SQL query to LINQ or lambda expression in C# and use in EF Core

I have 3 table
Tbl_City , Tbl_GroupCities , Tbl_CtrCar .
I want to convert this SQL query to LINQ or lambda expression in C#
declare #fk_group uniqueidentifier
SELECT #fk_group= FK_Group
FROM dbo.Tbl_User
WHERE UserName='meysam'
SELECT dbo.Tbl_City.ID_City, dbo.Tbl_City.Name_City,COUNT( dbo.Tbl_CtrCar.Cur_year)
FROM dbo.Tbl_City
INNER JOIN dbo.Tbl_CtrCar ON dbo.Tbl_City.ID_City = dbo.Tbl_CtrCar.FK_City
WHERE ID_City IN (SELECT FK_City
FROM dbo.Tbl_GroupCities
WHERE Active=1 AND ID_Group=#fk_group)
GROUP BY ID_City , Name_City
I try it but it's not work
var model = _TblUser.FirstOrDefault(x => x.UserName == "sampleUserName");
var q = _TblGroupCities.Where(x => x.IdGroup == model.FkGroup && x.Active == true);
var sample2 =
(from x in _TblCity
join a in _TblGroupCities on x.IdCity equals a.FkCity
where a.Active == true && a.IdGroup == model.FkGroup
select new
{
x.IdCity,
x.NameCity
}).ToList();
Please take a look here the features you have in your query are not yet implemented. GroupBy and i think also subselects will do an
SELECT * FROM TableName
And in memory it will do the group by or even for each row a new SQL query.
Better to use the RawSql method for this purpose.
But if you realy want to learn LINQ and convert your SQL take a look at LINQPad
This issue is done. I found my problem, I don't Understand use two joins and use group by in Linq
I use this linq for the solution and run
var model = _TblUser.SingleOrDefault(x => x.UserName == type.UserName);
var q = _TblGroupCities.Where(x => x.IdGroup == model.FkGroup && x.Active == true);
tblCityViewModel = new List<MohasebKhodro.ViewModels.TblCityViewModel>();
var sample2 =
(from x in _TblCity
join a in _TblGroupCities on x.IdCity equals a.FkCity
where a.Active == true && a.IdGroup == model.FkGroup
select new
{
x.IdCity,
x.NameCity
}).ToList();
foreach (var item in sample2)
{
var er = _TblCtrCar.Where(x => x.FkCity == item.IdCity).Max(x => x.CurYear);
tblCityViewModel.Add(new MohasebKhodro.ViewModels.TblCityViewModel
{
IdCity = item.IdCity,
NameCity = item.NameCity,
MaxCurrentYear = Convert.ToString(er)
});
}

How to Link two IDs from different classes in MVC5 to display certain information

I am trying to link up the RestaurantId in the RestaurantReservationEventsTbl with the RestaurantID in the RestaurantTbl to display reservations that are only made for the currently logged in restaurant.
I am receiving the following error in my code operator == cannot be applied to operands of type int and iqueryable int
Here is what I am doing in my home controller
var RestaurantIDRestaurantTbl = from r in db.Restaurants select r.RestaurantID;
//var listOfRestaurantsReservations = db.RestaurantReservationEvents.ToList();
var listOfRestaurantsReservations = db.RestaurantReservationEvents.Where(x => x.RestaurantID == RestaurantIDRestaurantTbl).ToList();
//return View(restaurants.Where(x => x.RestaurantEmailAddress == UserEmail).ToList());
//create partial view called _RestaurantReservation
return PartialView("_RestaurantReservations", listOfRestaurantsReservations);
You have to change your code to materialize the restaurantIds like this:
var RestaurantIDRestaurantTbl = (from r in db.Restaurants
select r.RestaurantID).ToList();
Then you may change the code as below for the comparison to work:
var listOfRestaurantsReservations = db.RestaurantReservationEvents.Where(x => RestaurantIDRestaurantTbl.Contains(x.RestaurantID)).ToList();
Anyway this is not the best solution. I will write another example for you, just try this example if it is working or not and let me know for the result.
I would considering changing the code as below to be much more efficient:
var listOfRestaurantsReservations = (from r in db.Restaurants
join e in db.RestaurantReservationEvents
on r.RestaurantID equals e.RestaurantID
//where r.RestaurantID == something //if where condition needed
select e).ToList();
If your tables are not connected with foreignkeys please consider to read this documentation here to make a better structure of the tables since they are related to each-other.
If your tables are related as in documentation article you might have something like that:
var RestaurantIDRestaurantTbl = db.Restaurants.SingleOrDefault(x => x.RestaurantID == something);
if(RestaurantIDRestaurantTbl != null)
{
var listOfRestaurantsReservations = RestaurantIDRestaurantTbl.RestaurantReservationEvents.ToList();
}
{
// This will give you a list of IDs
var RestaurantIDRestaurantTbl = db.Restaurants
.Select(p => p.RestaurantID)
.ToList();
// Using .Any() is a better choice instead of .Contains()
// .Contains is used to check if a list contains an item while .Any will look for an item in a list with a specific ID
var listOfRestaurantsReservations = db.RestaurantReservationEvents
.Where(p => RestaurantIDRestaurantTbl.Any(r => r.pRestaurantID == p))
.ToList();
}

LINQ - using result from one in another

I'm completely new to LINQ, i want to rewrite some of mine SQL querys into LINQ (just to learn) and i'v already stuck at the beginning. Probably solution is very simple but as i'v said I'm completely new and i didn't find solution to this.
I have one query :
string typMoneta = textBox1.Text;
var moneta = from x in db.grupyTowarowes
where x.typ == typMoneta
select new
{
x.grupa
};
Which works ok and when i set
dataGridView1.DataSource = moneta;
Then i got output
And i want to use this output in my second query :
var query = from c in dbContext.Picking
where c.Number == 1000 && c.Group == moneta
select new
{
c.id
};
Problem is with c.Group == moneta. I don't know the correct syntax. Could someone help me?
I think you meant to use moneta.Contains(c.Group). In first query, make sure you use ToList() to load data into memory.
IList<string> moneta = (from x in db.grupyTowarowes
where x.typ == typMoneta
select x.grupa).ToList();
var query = (from c in dbContext.Picking
where c.Number == 1000 && moneta.Contains(c.Group)
select c.id).ToList();
The moneta is an IEnumerable<T> where T in your case is the type of grupa
That being said you should write your query like below:
var query = from c in dbContext.Picking
where c.Number == 1000
&& moneta.Contais(c.Group)
select new
{
c.id
};
or in fluent syntax like below:
var query = dbContext.Picking
.Where(pick => pick.Number == 1000
&& moneta.Contains(pick.Group))
.Select(pick => pick.id);
Note that moneta is not a collection of strings. It's a collection of objects that have a string property named "grupa".
Does this work for you?
var query =
from c in dbContext.Picking
where c.Number == 1000
&& moneta.Any(m => m.grupa == c.Group)
select new { c.id };
You could also do this:
// Get list of strings
var groups = moneta.Select(m => m.grupa).ToList();
// Get items where "Group" value is one of the strings in groups list, above.
var query =
from c in dbContext.Picking
where c.Number == 1000
&& groups.Contains(c.Group)
select new { c.id };

Entity Framework Query Nested Query

I am new to the entity framework and am trying to convert the following query into the correct function calls.
Select Distinct a.nodeId FROM
(SELECT *
FROM reportContents
Where fitId = '29' and reportId =
(select max(reportId)
from reportContents
where fitId = '29')
) a Where (a.nodeId IS NOT NULL)
I know this query does what i want, however i'm not sure how to translate that into the entitiy framework!
Here was my attempt.
var prevSelectedNodes = db.reportContents.Where(
f => f.fitId == id).Select(
f => f.nodeId).Distinct().ToList();
I need to somehow put a .Select() in the where call. However that kind of thing dosen't seem possible
Thank you in advance!
As you can't make two LINQ nested lambda expression. You can do it with two requests :
var maxReportId = db.reportContents.Where(r => r.fitId = "29").Max(r => r.RepordId);
var result = db.reportContents.Where(r => r.fitId == "29" && r.reportId == maxReportId && r.nodeId != null).Select(a => a.nodeId).Distinct().ToList() ;

using linq to sql to specify where clause

I am using this method to get results to fill my grid but this method is also used to fill another grid which requires a where clause with two params and this one
only needs one. Even though i passed in null of the param that isn't used but still it is returning no results because of the where clause. Any advice of how i could
change this maybe use linq to sql where i call the method to specify the where clause instead of in the method getting data?
DocsForReview.DataSource = docLib.GetGrid(Guid.Empty, lib);
using (var dc = new DocMgmtDataContext())
{
var subs = (from doc in dc.Documents
join u in dc.Users on doc.OwnedByUserID equals u.ID
where doc.OwnedByUserID == usr && doc.LibraryID == lib
select new StudentDocuments
{
DocID = doc.ID,
Assignment = doc.Library.Name,
Submitted = doc.UploadDT,
Student = u.FullName
}).OrderByDescending(c => c.Submitted).AsEnumerable().ToList();
return subs;
}
For nullable types try this:
doc.LibraryID == (lib ?? doc.LibraryID)
In your case (a System.Guid) you can try this:
doc.LibraryID == (lib == Guid.Empty ? doc.LibraryID : lib)

Categories