razor set value of variable created by .query() method - c#

I have used the following code to get one more than the biggest ID in a table using razor
#foreach (var top in db.Query("SELECT MAX(ID)+1 as ID FROM mytable"))
{
if (#top.ID == null) {#top.ID = 1; }
}
if the table is empty, #top.ID returns null. I am trying to set its value to 1 if it is null. It however shows an error in the assignment part. How do you assign the value of #top.ID to something else? Or is there a way to user the sql query to set ID as 1 if the table is empty?

You can use
select isnull(max(ID),1) from YourTable
However, if you're trying to generate a new ID for a new record, you'd be better advised to use an identity field.

Related

how to get max id from a table using linq

I have a table Estimation which has an column EstimationNo,i am trying to get the max EstimationNo like this-
var result = cont.SalesEstimateCont.Where(x => x.Org_ID == CurrentOrgId);
var estimationMaxNo = result.Any() ? result.Max(x => x.EstimateNo) + 1 : 1;
var DigitalEstimate = new SalesEstimate()
{
EstimateNo=estimationMaxNo;
};
cont.Estimate.Add(DigitalEstimate );
cont.Savechanges();
but the problem is, if same table is saving by different users at same time its saving the same EstimationNo for both users. like- 10,10
Now, how to handle this issue..please give some solution.
Best strategy is to let db engine (I assume that it is SQL Server) handle incrementing of EstimateNo field. This can be done with identity specification which can be added to normal not primary key field also.
ALTER TABLE SalesEstimateCont drop column EstimateNo
go
ALTER TABLE SalesEstimateContadd Add EstimateNo int NOT NULL IDENTITY (1,1)
Please note: if you have existing data or some data should be modified, you may need some extra effort to achieve this (i.e with temp tables and by setting IDENTITY INSERT ON)
I got a simple answer.I just had to use transacationScope class.
and lock the resource table. like this-
using (TransactionScope scope = new TransactionScope())
{
cont.Database.ExecuteSqlCommand("SELECT TOP 1 * FROM Sales__Estimate WITH (TABLOCKX, HOLDLOCK)");
var result = cont.SalesEstimateCont.Where(x => x.Org_ID == CurrentOrgId);
var estimationMaxNo = result.Any() ? result.Max(x => x.EstimateNo) + 1 : 1;
var DigitalEstimate = new SalesEstimate()
{
EstimateNo=estimationMaxNo;
};
cont.Estimate.Add(DigitalEstimate );
cont.Savechanges();
}
If you can make EstimateNo an Identity column, that is the easiest/best way to fix this. If you can change this to a Guid, that would be another easy way to fix this as PK would be unique regardless of the user.
If you can't do either of these and you must take Max() manually, you might want to consider creating another table that stores the next available number there. Then you can create a new SqlCommnand with a Serializable transaction to lock the table, update the # by 1 and select it back. If two update commands hit at the same time, only one update will run and won't let go until that connection with Serializable transaction gets closed. This allows you to select the newly updated number before the other update runs and get the now "unique" next number.
You can OrderByDescending and then Take the the first record
var estimationMaxNo = result.OrderByDescending(x => x.EstimateNo).Take(1);
It can be done in a single command. You need to set the IDENTITY property for primary id
ALTER TABLE SalesEstimateCont ADD Org_ID int NOT NULL IDENTITY (1,1) PRIMARY KEY

Store Sql Function Value in string

I have function in SQL as above, i want the value 'INTERNATIONAL' stored in the string('strIntlStudent'). How can i accomplish that? I know data reader but column has no name.
string TSQL_INTERNATIONAL = "select TOP 1 campus6.dbo.fndqgetpopulation_of_YT_v2a ('P000170620', '2017', '03TERM')";
DataTable DT_INTERNATIONAL = dhelper.ExecuteSelectCommand(TSQL_INTERNATIONAL, CommandType.Text);
if (DT_INTERNATIONAL != null && DT_INTERNATIONAL.Rows.Count > 0)
{
strIntlStudent = DT_INTERNATIONAL.Rows[0]["it says no column name"].ToString();
}
You need to give your column a name. Try this:
select TOP 1 campus6.dbo.fndqgetpopulation_of_YT_v2a
('P000170620', '2017', '03TERM') AS some_name
Then you can use that name:
strIntlStudent = DT_INTERNATIONAL.Rows[0]["some_name"].ToString();
Alternatively, if you are only retrieving one value, then you can use ExecuteScalar function which returns one value regardless of the column name and you don't need to bother with a table. Check your dhelper class to see if it has a function related to ExecuteScalar.

How can I insert in database values from dropdown list based on a relationship between 2 tables? I am using ASP.NET c# Entity framework, Code first

I am not talking about the id of the element in the list, but the id of it from a table if the value is in another table. E.g I have a FullName and an ID in one table and I have the same ID and some other stuff in another table(one to zero or one relationship). I have bound the FullName to a dropdown list control,but when saving,I need to refer to it's ID from the table, not the string value.
If you place something in a drop down list, you can place the ID in the value field and something else as a text, for example :
ddlCategorie.DataTextField = "Texte";
ddlCategorie.DataValueField = "ID_GLOBAL";
ddlCategorie.DataSource = db.GLOBAL.Where(t => t.DATE_FIN > dt).OrderByDescending(t => t.ID_GLOBAL).ToList();
ddlCategorie.DataBind();
As you see, I already placed the reel database value "ID" of the object inside the value field of the drop down list. So I can immediately retrieve is ID by doing :
int i = Convert.ToInt32(ddlCategorie.SelectedValue);

Get present primary keys from link table, set Checkstate checklistbox

I have a CheckedListbox which contains values from some table called products.
The idea is to check the products that are associated to a customer. Now it does save correctly in an link table, yet when loading it again, the items that were checked do not get loaded correctly into the CheckedListbox.
So from that link table where, I would like to get all rows from just one column. All tables are already loaded into the application so I don't want to use sql.
I've tried using linq, with no success, Ids is just empty here.
int[] Ids = (from m in dataset.Tables["LinkTable"].AsEnumerable()
where m.Field<int>("customerId") == customerId
select m.Field<int>("productId")).ToArray();
Then, if I do succeed to get those Id's, I would like to get the indexes of those primary keys so I can set the correct products to checked.
I've tired doing it like this, but this gives me error in other parts of the program, because I am setting a Primary key to a global datatable. Datagridviews don't like that.
DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0] = dataset.Tables["products"].Columns["Id"];
currentPatient.GetTheDataSet.Tables["products"].PrimaryKey = keyColumns;
foreach (int Id in Ids)
{
DataRow row = dataset.Tables["Products"].Rows.Find(Id);
int index = dataset.Tables["Products"].Rows.IndexOf(row);
clbMedications.SetItemChecked(index, true);
}
I would like to do that last part without specifying a primary key, I couldn't find how to do that in linq.
I know it consists of 2 questions, but perhaps this can be done with just one linq statement so I better combine them.
[EDIT]
Finally, i think i've got what you need:
var qry = (from p in ds.Tables["products"].AsEnumerable()
select new {
Id = p.Field<int>("Id"),
Index = ds.Tables["products"].Rows.IndexOf(p),
Checked = ds.Tables["LinkTable"].AsEnumerable().Any(x=>x.Field<int>("productId") == p.Field<int>("Id") && x.Field<int>("customerId")==customerid)
}).ToList();
Above query returns the list, which you can bnid with CheckedListbox.

ASP.NET MVC Get value from two column to one column

I have two columns from excel file:
delivery_date1 - delivery_date2
2013-10-14 - null
null - 2013-10-19
I want to update deliveries table using the two columns from the uploaded excel file but in the my table, I only have one column which is the delivery_date.
What I would like to have is like this (based on the excel data above):
delivery_date
2013-10-14
2013-10-19
How can I do that using asp.net mvc?
Here's my code:
delivery_id = Convert.ToInt32(DB.db.Insert("dbo.deliveries", "delivery_id", new {
delivery_date = delivery_date1,
delivery_date = delivery_date2,
}));
I got an error like this:
An anonymous type cannot have multiple properties with the same name.
Which part of that error do you not understand? You cannot use the same property name twice!
I think this is what you want...
new
{
delivery_date = delivery_date1 == null ? delivery_date2 : delivery_date1
}
This will create a single property called delivery_date and will assign it the value of delivery_date1, or if delivery_date1 is null then it will be assigned with the value of delivery_date2

Categories