I am creating API to Get Data from Table.
My table is Tbl_Menu.
Id MenuName Status
-----------------------------------------------------
1 idli True
2 Utappa false
3 MeduWada True
i want data in API GET having only Status = true.
My Get API is
public IEnumerable<Tbl_Menu> GetTbl_Menu()
{
var tbl_menu = db.Tbl_Menu;
return tbl_menu.AsEnumerable();
}
I have to use Where Clause.
so what changes I suppose to do.
check this.
var tbl_menu = db.Tbl_Menu;
return tbl_menu.Where(t=> t.Status == true).ToList();
Related
I'd like to group my request by FkOperateur and FkPstStd but I still need information in the select new part. How should I proceed to get IdPoste, FkStandard, IsValidated, Date depending on the group part result
var shortFormations =
(from f in _context.Formations
where f.FkPstStdNavigation.FkPosteNavigation.FkZoneNavigation.FkBatimentNavigation.IdBatiment == Batiment && (f.FkOperateurNavigation.Equipe == Equipe || Equipe == null)
group f by new { f.FkOperateur, f.FkPstStd } into formation
select new shortFormations
{
FkOperateur = formation.Key.FkOperateur,
FkPstStd = formation.Key.FkPstStd,
IdPoste = f.FkPstStdNavigation.FkPosteNavigation.IdPoste,
FkStandard = f.FkPstStdNavigation.FkStandard,
IsValidated = f.IsValidated,
Date = f.DateFormation,
})
.AsNoTracking()
.ToList();
I can't get IdPoste FkStandard IsValidated and Date
return f doesn't exist on current context on these line.
Could you explain me please.
Select
fk_operateur,Fk_Pst_Std, max(date_formation)
FROM
Formations
GROUP by
Fk_Operateur,Fk_Pst_Std
that's a try in SQL but I'm not able to get others column mentionned before
returns
fk_operateur
FkPstStd
date_formation
1
1
Adate
and many other rows
Since its grouped, to access the mentioned fields, you will have to look in the Values and select the correct item. As in, something like
select new shortFormations
{
FkOperateur = formation.Key.FkOperateur,
FkPstStd = formation.Key.FkPstStd,
IdPoste = formation.FirstOrDefault()
.FkPstStdNavigation.FkPosteNavigation.IdPoste,
....
or order it and then select the correct record
I am not able to fetch a max value from a number field in AppMaker. The field is filled with unique integers from 1 and up. In SQL I would have asked like this:
SET #tKey = (SELECT MAX(ID) FROM GiftCard);
In AppMaker I have done the following (with a bit help from other contributors in this forum) until now, and it returns tKey = "NaN":
var tKey = google.script.run.MaxID();
function MaxID() {
var ID_START_FROM = 11000;
var lock = LockService.getScriptLock();
lock.waitLock(3000);
var query = app.models.GiftCard.newQuery();
query.sorting.ID._descending();
query.limit = 1;
var records = query.run();
var next_id = records.length > 0 ? records[0].ID : ID_START_FROM;
lock.releaseLock();
return next_id;
}
There is also a maxValue() function in AppMaker. However, it seems not to work in that way I use it. If maxvalue() is better to use, please show :-)
It seems that you are looking in direction of auto incremented fields. The right way to achieve it would be using Cloud SQL database. MySQL will give you more flexibility with configuring your ids:
ALTER TABLE GiftCard AUTO_INCREMENT = 11000;
In case you strongly want to stick to Drive Tables you can try to fix your script as follow:
google.script.run
.withSuccessHandler(function(maxId) {
var tKey = maxId;
})
.withFailureHandler(function(error) {
// TODO: handle error
})
.MaxID();
As a side note I would also recommend to set your ID in onBeforeCreate model event as an extra security layer instead of passing it to client and reading back since it can be modified by malicious user.
You can try using Math.max(). Take into consideration the example below:
function getMax() {
var query = app.models.GiftCard.newQuery();
var allRecords = query.run();
allIds = [];
for( var i=0; i<allRecords.length;i++){
allIds.push(allRecords[i].ID);
}
var maxId = Math.max.apply(null, allIds);
return maxId;
}
Hope it helps!
Thank you for examples! The Math.max returned an undefined value. Since this simple case is a "big" issue, I will solve this in another way. This value is meant as a starting value for a sequence only. An SQL base is better yes!
I have 2 tables as defined in the below image.
Now I want to query the "match table" with following checks;
UserA in FromUser
FromUser Rating is less than 0 or undefined.
Result should be:
Match Table Object
Must have count of meetings like UserA have 3 meetings with userB and 3 meetings with userC. so the result should be like following:
[{id:"",fromUser:"",toUser:"",MeetingCount:3},{id:"",fromUser:"",toUser:"",MeetingCount:3}]
How can I achieve this? What I tried so far:
I queried the match table and now I want to loop against each matchId from match detail table to get its data.
matQueryFrom.equalTo("FROM_USER_OBJECTID",user.id);
matQueryFrom.find().then(function(matchObjects){
if(matchObjects!=undefined && matchObjects.length>0){
var returnList = [];
for(var i=0;i<matchObjects.length;i++){
var vrmatchObj = matchObjects[i];
var matDetailQuery = new Parse.Query(Parse.Object.extend("VR_MATCH_DETAIL"));
matDetailQuery.equalTo("VRMatches", vrmatchObj.id);
matDetailQuery.find().then(function(detailArray){
returnList.push(detailArray);
}).then(function(){console.log(returnList);});
}
return returnList;
}
});
Can anyone guide me how can i achieve this? Currently the returnList is always empty.
I have a an array of objects that I want to enter into the database.
My method call looks like this.
public void Add(CardElement[] cardElements){
foreach (var cardElement in cardElements)
{
Data.Entry(cardElement).State = System.Data.EntityState.Added;
}
Data.SaveChanges();
}
The database table resembles this
MS SQL = Table mytable Columns a,b,c,d,e,f
Unique Constraint a,b,c
The data I want to insert resembles this.
var obj [] = new [] {
new MyObject () { a = 1, b =1, c = 1 },
new MyObject () { a = 1, b =1, c = 2 }
new MyObject () { a = 1, b =1, c = 3 }
};
So, I want to check the database for these three rows before I add them to the database.
I could do something like but I assume this should cause some extra trips to the database.
private bool checkExists()...
foreach (var cardElement in cardElements)
{
var exists = (from ce in Data.CardElements
where ce.CardId == cardElement.CardId
where ce.Area == cardElement.Area
where ce.ElementName == cardElement.ElementName
select ce).Any();
if(exists return true)
}
return false
So, how could I handle this more gracefully?
Is it even worth trying to accomplish this using linq?
Should I write some stored procedures for performance?
I agree that you should let the db make the decision.
Please have a look at using UPSERT as stated in this post
Why not just attempt the insert and let the database tell you if any unique constraint violations have occurred (using try/catch)?
The problem is that even if you query data somebody else can insert the record between your query and saving changes. You will still have to handle exception for violating unique constraint despite your additional queries - and yes, every check will do additional trip to database.
If your main concern is performance use stored procedure where you can additionally use table hint to lock table for inserts during initial check for existence.
I just asked this question. Which lead me to a new question :)
Up until this point, I have used the following pattern of selecting stuff with Linq to SQL, with the purpose of being able to handle 0 "rows" returned by the query:
var person = (from p in [DataContextObject].Persons
where p.PersonsID == 1
select new p).FirstOrDefault();
if (person == null)
{
// handle 0 "rows" returned.
}
But I can't use FirstOrDefault() when I do:
var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };
// Under the hood, this pattern generates a query which selects specific
// columns which will be faster than selecting all columns as the above
// snippet of code does. This results in a performance-boost on large tables.
How do I check for 0 "rows" returned by the query, using the second pattern?
UPDATE:
I think my build fails because I am trying to assign the result of the query to a variable (this._user) declared with the type of [DataContext].User.
this._user = (from u in [DataContextObject].Users
where u.UsersID == [Int32]
select new { u.UsersID }).FirstOrDefault();
Compilation error: Cannot implicitly convert type "AnonymousType#1" to "[DataContext].User".
Any thoughts on how I can get around this? Would I have to make my own object?
Why can you keep doing the samething? Is it giving you an error?
var person = (from p in [DataContextObject].Persons
where p.PersonsID == 1
select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }).FirstOrDefault();
if (person == null) {
// handle 0 "rows" returned.
}
It is still a reference object just like you actual object, it is just anonymous so you don't know the actual type before the code is compiled.
Update:
I see now what you were actually asking! Sorry, my answer no longer applies. I thought you were not getting a null value when it was empty. The accepted response is correct, if you want to use the object out of scope, you need to create a new type and just use New MyType(...). I know DevEx's RefactorPro has a refactoring for this, and I think resharper does as well.
Call .FirstOrDefault(null) like this:
string[] names = { "jim", "jane", "joe", "john", "jeremy", "jebus" };
var person = (
from p in names where p.StartsWith("notpresent") select
new { Name=p, FirstLetter=p.Substring(0,1) }
)
.DefaultIfEmpty(null)
.FirstOrDefault();
MessageBox.Show(person==null?"person was null":person.Name + "/" + person.FirstLetter);
That does the trick for me.
Regarding your UPDATE: you have to either create your own type, change this._user to be int, or select the whole object, not only specific columns.
if (person.Any()) /* ... */;
OR
if (person.Count() == 0) /* ... */;
You can still use FirstOrDefault. Just have
var PersonFields = (...).FirstOrDefault()
PersonFields will be be null or an object with those properties you created.