How to fetch 3 column values together from a table - c#

I have a table named CrewMembers which have 3 columns-FirstName,MiddleName and LastName.
I want to fetch the values of these 3 columns together using entity framework in a combobox in this format-
LastName,FirstName MiddleName
Here is the code for the same-
public IEnumerable GetCrewMember()
{
SASEntities db = DataContextFactory.GetSASEntitiesDataContext();
return (from cm in db.CrewMember
select
cm.LastName + "," +
cm.FirstName +" "+
cm.FullName
).ToList();
}
Now when I execute the code,I get only those names in the combobox which have all three values in the table but my MiddleName column can be left Null.Hence,I am not getting full names of those records which doesn't have a MiddleName.
How can I resolve this issue?

do this:
public IEnumerable GetCrewMember()
{
SASEntities db = DataContextFactory.GetSASEntitiesDataContext();
return (from cm in db.CrewMember
select new
{
CompleteName = cm.LastName + ","
+ cm.FirstName +" "
+ cm.FullName
}).ToList();
}

Related

SQL How to replace a value

I'm using a Database I was able to get all the data from the database and save it in a List<>. I made changes in the List<> using a DataGrid and now I want to replace each Database value for the List<> values WHERE the List.ID == Database ID. I use Dapper (In case it matters);
public void SetData(List<DatabaseInfoModel> database)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection("Server=.\\SQLEXPRESS; Database=XXXX; User Id=XXXX; Password=password;"))
{
foreach(DatabaseInfoModel item in database)
{
connection.Execute($"UPDATE DataTable " +
$"SET Name = {item.Name}, " +
$" Description = {item.Description}, " +
$" Record = {item.Record} " +
$" WHERE ID = {item.ID}");
}
}
}
you can pass a model, ex
.Execute("update mydogs set age=#Age where id=#Id",dog);
"dog" is your model
UPDATE DataTable
SET
Name = REPLACE(Name, item.Name, 'Replacement Value')
.
.
WHERE ID = {item.ID}
Is this what you are looking for ?
In case you are looking for the syntax, here is more information:
https://learn.microsoft.com/en-us/sql/t-sql/functions/replace-transact-sql?view=sql-server-ver15

mysql select command in C# with dynamic column names

I have a string in C# which has the column names of a table as shown below
shown_itemsName = "billno,department,date,subtotal,tea,coffee";
I want to display a table in dataGridView with column names that are there in the string (shown_itemsName) but when i write sql query
cmdDataBase.CommandText = "select #shown_itemsName from employee.transaction where department = #department AND MONTH(date) = #month_ AND YEAR(date) = #year_";
cmdDataBase.Parameters.AddWithValue("#shown_itemsName", shown_itemsName);
cmdDataBase.Parameters.AddWithValue("#department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("#month_", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("#year_", this.dateTimePicker1.Value.Year);
I get a table with only 1 column and 4 rows with the cell value as billno,department,date,subtotal,tea,coffee and the heading of that column also the same string.
Whereas I should be getting 6 columns and 4 rows as the result with the "," separated substrings as the column names
You cannot add new columns with parameters. If it is dynamic you don't have a choice but writing your query every time and execute a CommandType.Text command on it.
For every request, you must:
cmdDataBase.CommandText = "select " + shown_itemsName + " from employee.transaction where department = #department AND MONTH(date) = #month_ AND YEAR(date) = #year_";
cmdDataBase.Parameters.AddWithValue("#department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("#month_", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("#year_", this.dateTimePicker1.Value.Year);
using(var reader = cmdDataBase.ExecuteReader()) {
while(reader.Read()) {
// ...
}
reader.Close();
}

How to copy data from two different table and insert fetched records into another table

I am trying to insert data in my table which have 3 feild
(1) sendReqID type int(PK)
(2) RequestID type int (FK from table Request)
(3) DonorID type int (FK table Donor)
I know how to copy data from one table and insert into another table but I want to know how to insert data in table, when we have to extract values from two different tables. Following is my code which I am trying and unable to insert data into my table.
public void Req_SendID()
{
SqlConnection MySQL = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ToString());
string copy = "insert into Send_Request(RequestID,DonorID) Select RequestID,DonorID from RequestID and DonorID from Donor where R_City='" + Session["BGroup"] + "' and" + "D_City='" + Session["city"] + "'";
SqlCommand com = new SqlCommand(copy, MySQL);
MySQL.Open();
com.ExecuteNonQuery();
MySQL.Close();
}
Please Help thanks in advance.
You need to join on the two tables...
insert into Send_Request(RequestID,DonorID)
Select r.RequestID, d.DonorID
from RequestID r inner join Donor d ON r.R_City = d.D_City
where R_City='" + Session["BGroup"] + "' and " + "D_City='" + Session["city"] + "'"
I'm assuming the relationship is as above. However, consider SQL Injection attacks and look to parametrize your query.
EDIT: Using Parameterized Query
var requestCity = Session["BGroup"].ToString();
var donorCity = Session["city"].ToString();
"insert into Send_Request(RequestID,DonorID)
Select r.RequestID, d.DonorID
from RequestID r inner join Donor d ON r.R_City = d.D_City
where R_City=#RequestCity and D_City=#DonorCity"
SqlCommand com = new SqlCommand(copy, MySQL);
com.Parameters.Add("#RequestCity", requestCity);
com.Parameters.Add("#DonorCity", donorCity);
....
However, I just saw your comment that there is no relationship between the tables, so the actual query above would be incorrect.

Trying to insert into access database via SQL getting ID from another table

I have 2 tables in an Access database:
tblMachine
fields:
MachineID
MachineDescription
tblProblem
fields
ProblemID
MachineID
ProblemDescription
I am trying to add a new record into tblProblem, using the MachineDescription to find the MachineID from tblMachine
However, my SQL statement throws an error on the sub-select statement
Here is my statement:
string sql = "INSERT INTO tblProblem" +
" ([MachineID], [ProblemDescription], [ProblemOrder])" +
" VALUES (" +
"(SELECT ([MachineID] FROM tblMachine WHERE MachineDescription = #MachineDescription))," +
" #ProblemDescription, #ProblemOrder);";
The problem being highlighted is this part:
"(SELECT ([MachineID] FROM tblMachine WHERE MachineDescription = #MachineDescription)),"
Have I done something wrong? It is telling me there is a syntax error...
Extra set of parentheses, and perhaps unqualified field names:
String sql = "INSERT INTO tblProblem " +
"([MachineID], [ProblemDescription], [ProblemOrder])" +
"SELECT tblMachine.[MachineID], #ProblemDescription, #ProblemOrder " +
"FROM tblMachine " +
"WHERE tblMachine.MachineDescription = #MachineDescription";

Cannot insert duplicate key row in object with unique index 'in_name'

I get this error: Cannot insert duplicate key row in object with unique index 'in_name'
What can be the problem?
var ing = (from x in db.tblTable where x.ing_name == ing_name select x);
var ing1 = ing.First();
ing1.ing_name = ing1.ing_name + " (" + FormatC(ing_brand) + ")";
db.SaveChanges();
And here is FormatC:
public static string FormatC(string str)
{
if (!string.IsNullOrEmpty(str))
return str.Substring(0, 1).ToUpper() + "" + str.Substring(1).ToLower();
else
return "";
}
Got this answer from - https://www.sqlservercentral.com/forums/topic/cannot-insert-duplicate-key-row-in-object-with-unique-index-on-duplicate-foreing-key
Turns out that SQL Server, by default, sets indexed fields to allow only unique values. To check this, open the table in Design and select "Manage Indexes and Keys" option. Select the index/key listed and check the appropriate Yes/No drop down for the "Is Unique" property.

Categories