Update a single column to EF 6.0 using LINQ lambda ? MVC4 - linq

I want to save the data when i edit something in my data-table on enter .
On enter control goes to method in controller where actual update performs .
My code till this point:
public string UpdateData(int id, string value, int? rowId, int? columnPosition, int? columnId, string columnName)
{
var Leadsinfo = ser_obj1.Lead_List();
if (columnPosition == 0 && Leadsinfo.Any(c => c.Contact_Name.ToLower().Equals(value.ToLower())))
return "Lead with a name '" + value + "' already exists";
var Lead = Leadsinfo.FirstOrDefault(c => c.Lead_Id == id);
if (Lead == null)
{
return "Lead with an id = " + id + " does not exists";
}
switch (columnPosition)
{
case 0:
Lead.Contact_Name = value;
iWise_NeoEntities ooo = new iWise_NeoEntities();
break;
case 1:
Lead.Contact_Address = value;
break;
case 2:
Lead.Lead_Source = value;
break;
case 3:
Lead.Domain = value;
break;
default:
break;
}
return value;
}
In the above code i mentioned i need to write logic where it should save to DB upon any column editing . using lambda linq is easy i guess , But i dont know even how to start ?
Do i need to write save under each case?

You can create update method in database:
public void UpdateLead(Lead model)
{
var entity = db.Set<Lead>().Find(model.Id);
db.Entry<Lead>(entity).CurrentValues.SetValues(model);
db.SaveChanges();
}
And use it where you need:
switch (columnPosition)
{
case 0: Lead.Contact_Name = value; break;
case 1: Lead.Contact_Address = value; break;
case 2: Lead.Lead_Source = value; break;
case 3: Lead.Domain = value; break;
default: break;
}
iWise_NeoEntities ooo = new iWise_NeoEntities();
ooo.UpdateLead(Lead);

Related

Got Null result from Oracle even though the real result are decimal value

I am new to Oracle in Visual Studio,
I used Oracle.ManagedDataAccess as my reference,
The case is whenever I tried to retrieve decimal value from arithmetic in Oracle query, Its always return null
e.g
SELECT 26/3 FROM DUAL < ---- This code return null in my visual studio but has a value in TOAD.
Did I do it wrong ?
Here is my code to retrieve the value
List<object[]> result = new List<object[]>();
OracleDataReader data;
string constr = ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
string query = QueryString;
using (OracleCommand cmd = new OracleCommand(query))
{
cmd.Connection = con;
con.Open();
data = cmd.ExecuteReader();
try
{
if (data.HasRows)
{
while (data.Read())
{
object[] itemData = new object[data.FieldCount];
//Dictionary<string, string> itemData = new Dictionary<string, string>();
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
if (typeof(string) == type)
{
itemData[i] = data.GetString(i);
}
if (typeof(DateTime) == type)
{
itemData[i] = data.GetDateTime(i);
}
if (typeof(int) == type)
{
itemData[i] = data.GetInt32(i);
}
if (typeof(decimal) == type)
{
itemData[i] = data.GetDecimal(i);
}
if (typeof(bool) == type)
{
itemData[i] = data.GetBoolean(i);
}
if (typeof(TimeSpan) == type)
{
itemData[i] = data.GetTimeSpan(i);
}
if (typeof(Single) == type)
{
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
}
}
result.Add(itemData);
}
}
else
{
Console.WriteLine("Rows not found.");
}
}
finally
{
data.Close();
}
con.Close();
}
}
return result;
UPDATED : It got null just for division which has decimal value. Addition, Substraction, multiplication has no issue
It seems your data type doesn't match any of your if expressions. As there is no default branch, itemData[i] remains null. I suggest something like the following to find the gap:
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
switch(type)
{
case typeof(string):
itemData[i] = data.GetString(i);
break;
case typeof(DateTime):
itemData[i] = data.GetDateTime(i);
break;
case typeof(int):
itemData[i] = data.GetInt32(i);
break;
case typeof(decimal):
itemData[i] = data.GetDecimal(i);
break;
case typeof(bool):
itemData[i] = data.GetBoolean(i);
break;
case typeof(TimeSpan):
itemData[i] = data.GetTimeSpan(i);
break;
case typeof(Single):
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
break;
default:
MessageBox.Show("Unknown type " + type.Name);
break;
}
}
So, I got an advice to edit the oracle query
From (e.g.)
SELECT 26/7 FROM DUAL
TO
SELECT TO_CHAR(26/7) FROM DUAL
And yes it works
But still, I don't know why

Search for particular column and update it in linq EF 4.0

Basically table contain about 50 columns and I have to search for that particular column and update it.
lets say val == 27 then columnName will be Alarm27 and the "onOff" value I have to set in that Alarm27 column.
But question is how do I get this Alarm27 and just update it.
This is what I have tried so far.
public void UpdateAlarm(int val, bool onOff)
{
string alarmName = "Alarm" + val;
using (ESEntities context = new ESEntities())
{
var alarmid = context.OffShoreAlarms.Where(p => p.StationID == (int)TMStation.LQ).Select(p => p.OSAlarmID).FirstOrDefault();
var alarmMonitor = context.OfSAlarmMonitors.Where(p => p.OSAlarmID == alarmid).Select(p => p).FirstOrDefault();
switch (val)
{
case 1:
alarmMonitor.Alarm1 = onOff;
context.saveChanges();
break;
case 2:
alarmMonitor.Alarm2 = onOff;
context.SaveChanges();
break;
.
.
.
.
case 50:
alarmMonitor.alarm50 = onOff;
context.saveChanges();
break;
}
//TODO: context.SaveChanges(); do update operation..
}
}
I have not practically tried this but I think this may work for you.
string alarmName = "Alarm" + val;
context.OffShoreAlarms.Property(alarmName).CurrentValue = true;
You can change current Value of Your entity like this.
For more info check this Link

How should I be using the Kentico TreeNode.Update method?

I am trying to run the attached code to update some data for a particular document type but it is not actually updating anything.
My currentDocumentNodeId() method is pulling back a NodeId based on some other criteria and then each of these Nodes that it is getting is of the type HG.DocumentLibraryItem which have the columns IsPublic, IsRepMining, IsRepPower, IsRepProcess, and IsRepFlexStream. But when I call the update method and then pull back those Columns in the SQL table for this Custom Document Type, the values are all Null. Each of those columns in the HG.DocumentLibraryItem document type are set to boolean I have tried using the Node.SetValue() method and setting it to true and 1; neither way works to update that column.
Any ideas what I am doing wrong? Am I doing the call correctly?
See my code below:
public static void GetDocumentAreaAssignments()
{
var cmd = new SqlCommand
{
CommandText ="This is pulling back 2 rows, one with Id and one with Text",
CommandType = CommandType.Text,
Connection = OldDbConnection
};
OldDbConnection.Open();
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
var count = 0;
while (rdr.Read())
{
try
{
var documentId = TryGetValue(rdr, 0, 0);
var areaAssignment = TryGetValue(rdr, 1, "");
var currentDocumentNodeId = GetNodeIdForOldDocumentId(documentId);
var node = currentDocumentNodeId == 0
? null
: Provider.SelectSingleNode(currentDocumentNodeId);
if (node != null)
{
switch (areaAssignment.ToLower())
{
case "rep mining":
node.SetValue("IsRepMining", 1);
break;
case "rep power":
node.SetValue("IsRepPower", 1);
break;
case "rep process":
node.SetValue("IsRepProcess", 1);
break;
case "rep flexStream":
node.SetValue("IsFlexStream", 1);
break;
case "public":
node.SetValue("IsPublic", 1);
break;
}
node.Update();
Console.WriteLine("Changed Areas for Node {0}; item {1} complete", node.NodeID,
count + 1);
}
}
catch (Exception ex)
{
}
count++;
}
}
}
catch (Exception)
{
}
OldDbConnection.Close();
}
The coupled data (as IsRepMining field) are only updated when you retrieve a node that contains them. To do that you have to use overload of the SelectSingleNode() method with a className parameter. However I'd recommend you to always use the DocumentHelper to retrieve documents. (It will ensure you work with the latest version of a document...in case of workflows etc.)
TreeProviderInstance.SelectSingleNode(1, "en-US", "HG.DocumentLibraryItem")
DocumentHelper.GetDocument(...)
DocumentHelper.GetDocuments(...)

C# linq and sorting

With linq I want to use order by with specific column but I need two switches because i don't know how to use desc or asc in one
public class CustomersRepository : RepositoryBase<Customers>
{
public List<Customers> GetAll(CustomersProperties property, SortEnum sortEnum, int page, int limit)
{
var query = _context.Set<Customers>();
switch (sortEnum)
{
case SortEnum.Ascending:
switch (property)
{
case CustomersProperties.Name:
query = query.OrderBy(x => x.Name);
break;
case CustomersProperties.Surname:
query = query.OrderBy(x => x.Lastname);
break;
default:
throw new ArgumentOutOfRangeException("property");
}
break;
case SortEnum.Descending:
break;
default:
throw new ArgumentOutOfRangeException("sortEnum");
}
return query.Skip(page * limit)
.Take(limit).ToList();
}
}
Is it possible to do without two switch cases?
Be aware that query.OrderBy(x => x.Name); does not do anything since the sorted collection is returned from OrderBy, and you're not capturing that return.
That said, there's not a way to "dynamically" choose the direction in Linq. However, a conditional switch would be a little cleaner. Another option would be to capture the sort expression in a variable:
Expreccion<Func<Customers, string>> propExp;
switch (property)
{
case CustomersProperties.Name:
propExp = ((Customers)x => x.Name)
break;
case CustomersProperties.Surname:
propExp = ((Customers)x => x.Lastname);
break;
default:
throw new ArgumentOutOfRangeException("property");
}
query = sortEnum == SortEnum.Ascending
? query.OrderBy(propExp);
: query.OrderByDescending(propExp);
You could make your own overload, something like this:
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(
this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector, SortEnum sort) {
switch (sort) {
case SortEnum.Ascending:
return source.OrderBy(keySelector);
case SortEnum.Descending:
return source.OrderByDescending(keySelector);
default:
throw new ArgumentOutOfRangeException("sort");
}
}
// later on..
query = query.OrderBy(x => x.LastName, sortEnum);
You can prepare sortProperty Expression first and then use it with either OrderBy or OrderByDescending:
public List<Customers> GetAll(CustomersProperties property, SortEnum sortEnum, int page, int limit)
{
var query = _context.Set<Customers>();
Expression<Func<Customers, string>> sortProperty;
switch (property)
{
case CustomersProperties.Name:
sortProperty = x => x.Name;
break;
case CustomersProperties.Surname:
sortProperty = x => x.Lastname;
break;
default:
throw new ArgumentOutOfRangeException("property");
}
switch (sortEnum)
{
case SortEnum.Ascending:
query = query.OrderBy(sortProperty);
break;
case SortEnum.Descending:
query = query.OrderByDescending(sortProperty);
break;
default:
throw new ArgumentOutOfRangeException("sortEnum");
}
return query.Skip(page * limit)
.Take(limit).ToList();
}

NPOI does not evaluate 3d formula

I'm using NPOI to read data from Excel 2003 files. These files contains formulas like this SUM('1:2'!$C$17). NPOI recognized such formulas like SUM('1'!$C$17) (w/o sheet 2) and evaluate invalid result.
I'm using a regular code from NPOI examples, like
foreach (var row in docRows)
{
sb.AppendFormat("{0}\t", SomeCode);
rowCounter += 1;
sb.AppendFormat("{0}\t", rowCounter);
foreach (var col in docColumns)
{
ICell cell = sheet.GetRow(row).GetCell(col);
sb.AppendFormat("{0}\t", GetExcelCellValue(cell));
}
sb.AppendLine();
}
private string GetExcelCellValue(ICell cell)
{
string cellValue = string.Empty;
IFormulaEvaluator evaluator = _hssfworkbook.GetCreationHelper().CreateFormulaEvaluator();
evaluator.Evaluate(cell);
switch (evaluator.EvaluateInCell(cell).CellType)
{
case CellType.BLANK:
cellValue = string.Empty;
break;
case CellType.BOOLEAN:
cellValue = string.Empty;
break;
case CellType.NUMERIC:
cellValue = Convert.ToString(cell.NumericCellValue); //This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number.
break;
case CellType.STRING:
throw new ArgumentNullException();
cellValue = cell.StringCellValue;
break;
case CellType.ERROR:
cellValue = string.Empty;
break;
case CellType.FORMULA:
break;
}
return cellValue;
}
I have just encountered this problem and I solved it by
switch (cell.CellType)
{
case CellType.Blank:
cellValue = "";
break;
case CellType.Boolean:
cellValue = cell.BooleanCellValue.ToString();
break;
case CellType.Formula:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.Numeric:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.String:
cellValue = cell.StringCellValue;
break;
}

Resources