Table contains particular value or not - c#

I am using linq to sql and my Datatable(tbl_final_aut) seems as
and I made a select query in my appliaction as
.cs code
var sel = db.selectdoc(24).ToList();
if (sel.Count == 3)
{
//all doc are uploaded
}
else
{
//
}
on seeming my Datatable we can see that I will go in if condition but I want that if my sel.count=2 or sel.count=1 than I want to show that which groupname or type is not there in my datatable
For example :
if my datatable seems to be
so my condition will go to else and there I want to get my alert box that other 2 groupname is not there like
var sel = db.selectdoc(24).ToList();
if (sel.Count == 3)
{
//all doc are uploaded
}
else
{
//I want in alert that "cover letter and CopyrightTra.. is not present"
}
Store procedure code is
ALTER PROCEDURE dbo.selectdoc
#art_aut_id int
AS
select * from tbl_final_aut where art_aut_id=#art_aut_id
RETURN
As you see actually I have only 3 types as you seen in my 1st datatable that is 1,3,4..I just want to know that if any one type says to be 3rd type is not there or present in table than my sel.count=2 so it will go in else condition and there I have to make some code which says that type 3 or coverletter is required to be upload.what code shall I make over there
error
datatype

string[] groupNames = { "Main Article", "Cover Letter" }; // list all groups
var missingGroups =
groupNames.Except(db.selectdoc(24).Select(d => d.groupname).Distinct());
You can also get all group names from database without hard-coding them in code:
string[] groupNames = db.tablename.Select(d => d.groupname).Distinct().ToArray();

Related

Entity Frame Navigation property for table joins

I have 3 tables namely Ship[ShipID, Name, YearOfConstr, CompanyID(FK), TypeID(FK)] which is a bridge between Company[CompanyID, Name, Headquarter] and Type[TypeID, Description, NoPassengers]
I wanted to query the names of all Company which has a specific type = "xxx" and whose headquater = "yyy"
Below is what I have tried, but it's returning nothing and won't throw an error either.
public List<string> AllShippingCompanies(string TypeDescription, string headquarters)
{
var list = from shipcomany in dbContext.Ships.Where(x => x.Type.Description == TypeDescription && x.ShippingCompany.Headquarter == headquarters)
select shipcomany.ShippingCompany.Name;
return list.ToList();
}
What could I have been doing wrong ?
I just check and found there are no related data in my DB. The code works fine. It's correct. Thanks for your time

Linq to Dataset C#

So I have a table called groupe_stg it contains 2 foreign keys code_demande , code_stagiaire and at the same time they are primary keys.
In my app I have the code_stagiaire and from it I want to retrieve it's code_demande. Basically what am trying to say is:
select code_demande
from group_stg
where code_stagiaire = "parameter"`
I would've create a stored procedure it would be easier , but unfortunately I was forced to work with an access database
This is my solution for the LINQ code,
String code_linq()
{
var query = from g in Program.mds.group_stg
where g.cin_stagiaire == txt_cin.Text
select new
{
code = g.code_demande
};
return query.ToString();
}
As you can see it is some sort a scalar function
but this code is giving me this exception:
system.data.enumerablerowcollection'1 [<>
f_anonymousType0'1[System.String]]
You are selecting multiple code_demande in an anonymous type but you want a single string.
If you just want the first code_demande which has cin_stagiaire == txt_cin.Text:
var demands = from g in Program.mds.group_stg
where g.cin_stagiaire == txt_cin.Text
select g.code_demande;
return demands.FirstOrdefault(); // null if no match

How can I use a where clause and check if a string variable contains in a many table column

I have made an method that will check if name value contains in the name column on current table, but I also need to see if the name contains in another column that is in a many table(TABLE.Project).
TABLE.Customer 1 --- *(many) TABLE.Project(Which have column named "Name")
This is the method:
Public List<SearchObject> Finditem(string name)
{
var query = from o in db.tbl_Custommer
where o.Name.Contains(name)
select new SearchObject
{
Url = o.tbl_Webs.WebUrlName,
Name = o.Name,
};
return query.ToList();
}
Do I need to iterate throught each o.Project?
Any kind of help is appreciated alot!
presuming you have the relationship correctly setup and its called Projects then you could use any - i.e. return customers where the name matches name and they have at least one project with the name also matching:
var query = from o in db.tbl_Custommer
where o.Name.Contains(name) && o.Projects.Any(p => p.Name.Contains(name))
select new SearchObject
{
Url = o.tbl_Webs.WebUrlName,
Name = o.Name,
};

C# report edit column values

I'm generating a report based on a database table. In the table I have genders saved as either 0 or 1 (male/female). In the report I would like to show the string value rather than showing the numbers. I tried messing with the code, ie.
this.ItemsTableAdapter.Fill(this.InventoryDataSet.Items);
foreach (DataRow row in this.InventoryDataSet.Items.Rows)
{
if (row["gender"].ToString() == "0")
{
row["gender"] = "Male";
}
}
this.reportViewer1.RefreshReport();
However this breaks the report complelty (no data is shown). How can I achieve what I want?
[edit]
I came a little closer to the solution (I think) with this:
this.InventoryDataSet.Items.Columns.Add("genderVerbose", typeof(string));
foreach (DataRow row in this.InventoryDataSet.Items.Rows)
{
if (row["gender"].ToString() == "0")
{
row["genderVerbose"] = "Male";
}
}
However now I get this error when trying to use the field in the report:
Error 2 The Value expression for the text box ‘color’ refers to the
field ‘genderVerbose’. Report item expressions can only refer to
fields within the current dataset scope or, if inside an aggregate,
the specified dataset scope. Letters in the names of fields must use
the correct case.
How about assigning Enum values to the cells? Enum.ToString() by default gives the value name in code as the string. So with:
public enum Gender { Male, Female }
You can just shove those into DataGridView cells and it will show that way. You can test values by
if ((Gender)row["gender"].Value == Gender.Male)
{
// do things...
}
If you need this to be user-selectable, you can use the DataGridViewComboBoxCell.

C# Comparing data with database by using array

My database contains 2 records. So, I retrieve these 2 records and store in array. Let's say my database have start point, destination, terminal and departure time. If user trying to add same start point, same destination, same terminal and same departure time, it will show error message. But if user trying to add same start point, same destination, same terminal but DIFFERENT departure time. It suppose to allow user add, but I having problem with user not allow to add.
Example:
These record are in my database
Record 1 : Terminal = 1 , From = US , To = UK, Time = 10.00
Record 2 : Terminal = 1 , From = US , To = AUS , Time = 2.00
When user want to add new record
User wish to add: Terminal = 1, From = US, To = AUS, Time = 10.00
It's tell me record exist because the time 10.00 exist in other record which is in different destination. Anyone can help?
if (ow_terminal.Any(s => ddlterminal.SelectedValue.Contains(s))
&& ow_depart.Any(s => ddlDeparture.SelectedValue.Contains(s))
&& ow_origin.Any(s => ddlOrigin.SelectedValue.Contains(s))
&& ow_destination.Any(s => ddlDestination.SelectedValue.Contains(s)))
{
lblMessage.Text = "Record exist";
}
else
{
lblMessage.Text = "No record exist"
}
The problem is with your Linq statement.
Think logically about what it is actually saying:
if(terminal_array.Any(s => new_terminal_record.Contains(s)))
So if ANY of the values in your terminal_array matches the new terminal record that the user entered then this statement is true, and your code will then evaluate the next line
if(depart_array.Any(s => new_depart_record.Contains(s)))
And it will do the same thing, if ANY of the values in your depart array matches the new departure record that the user entered then this statement is also true.
What you most likely want to do is to store the records in an array of whatever your record type is and do the Linq statement over each record in that array, something along the lines of:
if(records_array.Any(s => new_record.terminal.Equals(s.terminal) &&
new_record.depart.Equals(s.depart) &&
new_record.origin.Equals(s.origin) &&
new_record.destination.Equals(s.destination)))
{
// Record Exists
}
else
{
// No Record Exists
}
For a more complete example, I have replicated your implementation and then included my implementation:
class Program
{
// Example of database records
struct _dbTypes
{
public string terminal;
public string depart;
public string origin;
public string destination;
};
static void Main(string[] args)
{
// First record
_dbTypes record1;
record1.terminal = "1";
record1.depart = "10.00";
record1.origin = "US";
record1.destination = "UK";
// Second record
_dbTypes record2;
record2.terminal = "1";
record2.depart = "2.00";
record2.origin = "US";
record2.destination = "AUS";
// Your implementation has each of the records internals
// separated into their own array
List<String> terminals = new List<string>();
List<String> departs = new List<string>();
List<String> origins = new List<string>();
List<String> destination = new List<string>();
terminals.Add(record1.terminal);
terminals.Add(record2.terminal);
departs.Add(record1.depart);
departs.Add(record2.depart);
origins.Add(record1.origin);
origins.Add(record2.origin);
destination.Add(record1.destination);
destination.Add(record2.destination);
// The NEW record that the user has entered
_dbTypes record3;
record3.terminal = "1";
record3.depart = "10.00";
record3.origin = "US";
record3.destination = "AUS";
// Example of your implementation
if (terminals.Any(s => record3.terminal.Contains(s)) &&
departs.Any(s => record3.depart.Contains(s)) &&
origins.Any(s => record3.origin.Contains(s)) &&
destination.Any(s => record3.destination.Contains(s)))
{
// Will fall into here
Console.WriteLine("Record exists");
}
else
{
Console.WriteLine("No record exists");
}
// What you should probably be doing...
//
// Array of your record type
List<_dbTypes> dataBaseEntries = new List<_dbTypes>();
//
// Add the first two records as a whole record, not separated out
dataBaseEntries.Add(record1);
dataBaseEntries.Add(record2);
// Now you want to do the Linq statement over the record
// AND'ing each .Equals on the current records internal objects
if (dataBaseEntries.Any(s => record3.terminal.Equals(s.terminal) &&
record3.depart.Equals(s.depart) &&
record3.origin.Equals(s.origin) &&
record3.destination.Equals(s.destination)))
{
Console.WriteLine("Record exists");
}
else
{
Console.WriteLine("No record exists");
dataBaseEntries.Add(record3);
}
}
}
From what I can tell, you seem to be storing the information for each record in separate arrays, one each for terminal, depart, origin, and destination. This is a bit problematic since there isn't a concrete way of determining that the information belongs to the same record UNLESS for some reason, the information are ordered in the array per record:
example:
ow_terminal[0] = 1
ow_depart[0] = "US"
ow_origin[0] = "UK"
ow_destination[0] = 10.00
If this is the case, then you have to change your if statement logic. I don't think LINQ can help in this case, but you can try:
bool exists = false;
for(int i = 0; i < ow_terminal.Count; i++)
{
if(ddlterminal.SelectedValue.Contains(ow_terminal[i])
&& ddlDeparture.SelectedValue.Contains(ow_depart[i])
&& ddlOrigin.SelectedValue.Contains(ow_origin[i])
&& ddlDestination.SelectedValue.Contains(ow_destination[i]))
{
exists = true;
break;
}
}
if(exists) lblMessage.Text = "Record exist";
else lblMessage.Text = "No record exist";
The code checks the values of each array in the same position for equality. Again, this would only work if the items on all of the arrays are arranged per record. ALSO, you may want to change the equality check since Contains may not be best fit for your purpose ("US" is contained in "RUSSIA", for example.)
HOWEVER, managing four arrays and making sure that they are ordered correctly all the time is very fragile. What you want to do is to create just one array (or list) of objects that correspond to your record with corresponding properties:
public class FlightRecord
{
public int Terminal {get;set;}
public string From {get;set;}
public string To {get;set;}
public decimal Time {get;set;} // How are you storing time?
}
Create an array of FlightRecords from your database records and then you can do your logic like you wanted with a few minor changes:
if (ow_flightrecords.Any(s => ddlterminal.SelectedValue.Contains(s.Terminal.ToString()
&& ddlDeparture.SelectedValue.Contains(s.Time.ToString())
&& ddlOrigin.SelectedValue.Contains(s.From)
&& ddlDestination.SelectedValue.Contains(s.To)))
{
lblMessage.Text = "Record exist";
}
else
{
lblMessage.Text = "No record exist"
}
This one is more robust and you can use LINQ easily. Again, change how you do the comparisons since Contains may not be as good a fit for your purpose as you think it is.
And as Synchro noted, it's probably a good idea to do the check on the database directly via a stored procedure before you do the actual INSERT into the database. It will be much faster this way.

Categories