SumAsync() with nvarchar value - asp.net-mvc

I have tbl_purchase table which has fields such as order_date - DateTime,price - nvarchar, pid - int etc., Requirement is to display total price with respect to each year in a chart. So to get the price, I decided to go with SumAsync. But the problem here is price field will be stored appended with $ as in $12,234.03,$4,453.23 etc., and as mentioned it is a nvarchar field. I Tried splitting the value within SumAsync() but was getting compilation error. Totally blank on how to work with this? Any work-around to split the $ and sum up the values? Below is what I tried.
ChartData.cs
public class ChartData
{
public string period {get;set;}
public int purchase {get;set;}
public string purchaseAmount {get;set;}
}
Controller method
var areaModel = new List<ChartData>();
var yearList = new string[]{'2015','2016'};
foreach (var year in yearList)
{
int yr=Convert.ToInt32(year);
var model = new ChartData
{
period = year,
purchaseAmount=await context.tbl_purchases.Where(x=>x.order_date.Year == yr).SumAsync(x=>(long)x.price.Split('$')[1]); //shows complie error. Its expecting `long` but the conversion doesn't happen well here.
};
areaModel.Add(model);
}

if price format is computed and always the same you can do as follow to calculate the price:
var price = new List<string> { "$4,000.99","$20.99","$40,000.88"};
var sum = price.AsEnumerAble().Sum(x => double.Parse(x.Replace("$", "0")));
I just replace the $ with 0 and calculate the sum.

Related

How to put a column from a database table into a dynamic list?

For my Project I want to access the database especially one table which has the BauTeilId in it and putting all the BauTeilId into one List in the Controller
DefaultConnection:
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=QualitätsKontrolleDB;Trusted_Connection=True;MultipleActiveResultSets=true"
Controller
The String Code is from the HTML and consits of 6 digits
private ApplicationDbContext Context = new ApplicationDbContext();
[HttpGet]
public IActionResult StartPage(string Code)
{
Debug.WriteLine(Code);
var list = Context.Result.All(c => c.BauTeilId);
return View();
}
Table used for this
I only need the BauTeilId
TypenID int
PruefungenID int
BildID int
BauTeilID string
Date DateTime
xLabel string
X int
YLabel string
Y int
FehlerCode string
Fehlername string
FehlerGruppe1 string
FehlerGruppe2 string
Result int
Right now the output is not existent but it should be the whole column.
If to want to get only BauTeilId from table likeselect BauTeilId from table use
(from t in Context.Result
select new {
t.BauTeilId
}).toList(); // .toList(); is not necessary, Linq returns an `IEnumerable `
That LINQ Statement,Hope you get point.
You can take list of any columns you want like this :
var myDynamicList = Context.Result.Select(c=> new { c.BauTeilId }).ToList();
this will be a List of dynamic type. For example you can call first element BauTeilId like this :
myDynamicList.First().BauTeilId;

zeros at start were not fetching while reading the table data in specflow

I want to read table data from the specflow feature file.
Table value is '000085'
When I create a sales quotation from the table:
| CustomerAccount |
| 000085 |
//Code:
public void CreateSalesQuotation(Table table)
{
dynamic tableData = table.CreateDynamicInstance();
int x = tableData.CustomerAccount;
}
Result:
Expected value is 000085 but actual value i am getting in x variable is 85
What is the version of specflow?
Better you use CreateInstance rather than CreateDynamicInstance to avoid extra operation on string.
public void CreateSalesQuotation(Table table)
{
var tableData = table.CreateInstance<Customer>();
var value = tableData.CustomerAccount;
}
internal class Customer
{
public string CustomerAccount { get; set; }
}
Result: Expected value is 000085 and actual value is 000085
There are two solutions: Using this as a string from the start. Since probably in the database this is a char or varchar as well (similar to string).
string x = tableData.CustomerAccount;
//value is 000085
Or you could manipulate the integer to a string with leading zeros.
int x = tableData.CustomerAccount;
//now it is 85
string y = x.ToString();
//we convert to string so we can use padleft
string z = y.PadLeft(2, '0');
//this will add 2 zeros to the beginning of the string.
Ofcourse you would want to optimize this last bit so that the leading zeros are correct.

Getting values from Bind. One key returns "0"

I want to make a few strings out of the Bind values. Easy enough except that one of them is messing with me. _surveyID = "0"
SurveyController:
public ActionResult Create([Bind(Include = "SurveyID,SurveyName,SenderID,ConsultantID,ResponderID,Question1,Question2,Question3,Question4,Question5,SurveyTime")] Survey survey)
{
if (ModelState.IsValid)
{
string _surveyID = survey.SurveyID.ToString();
string _surveyName = survey.SurveyName;
string _surveyTime = survey.SurveyTime.ToString();
//ANOTHER ATTEMPT, SAME RESULT
//string _surveyID = db.Surveys
//.FirstOrDefault(x => x.SurveyID == survey.SurveyID)
//.SurveyID;
}
SurveyID to database = 1002
SurveyID to my _surveyID = "0"
Notice that _surveyName and _surveyTime are both working fine.
The survey Bind values: http://i.imgur.com/khEDUns.png
Why is my SurveyID beeing set to 0 when I try to pull out the value?
EDIT: Is the ID value created when beeing put into database? Is my code too soon in the flow of code?
EDIT2: This is a bump1

Searching a table based upon guid value

I need to find a row in a table based upon Guid value. This is what I've currently been doing and doesn't work.
I have a following function
public ActionResult Details(long id)
{
var ownerId = _dbSis.OwnedModules.Find(id);
var ownerName = _dbCore.BusinessUnits.Find(ownerId.ModuleOwnerId);
var moduleV = (_dbSis.Modules.Select(module => new ModuleDetails
{
Id = id,
ModuleId = module.ModuleId,
TypeName = module.ModuleType.TypeName,
KindName = module.ModuleType.ModuleKind.KindName,
Owner = ownerName.Name,
}));
return View(/*moduleV.FirstOrDefault()*/);
}
Currently I get null value in ownerName whereas in ownerId value is passed.
Here is the image of of what is passed in ownerId
Here is the image of the BusinessUnits table
Why isn't my _dbCore.BusinessUnits.Find(ownerId.ModuleOwnerId) not working or finding any value? Isn't it possible to Find some row based on Guid Value?

Entity Framework is not returning the proper data. It is repeating data from a single record

Using MVC 4 with EF code First.
When doing linq to EF selects statements, the collections are being populated with what seems like the last record's data. And what's weirder, only some of the properties are repeated where others are not. It is best to show you by example:
Using this query returns the proper data:
var orders = db.Orders.ToList();
OrderID OrderTotal Name
1 215.00 Bob
2 415.00 Mark
3 315.50 Ralph
When I filter the Orders entity by a SubscriberID, which is a foreign key, like so:
var orders = db.Orders.Where(s => s.SubscriberId == 2).ToList();
The data end up looking like this:
1 315.50 Bob
2 315.50 Mark
3 315.50 Ralph
Notice how the OrderTotal is repeated but the names stay the same. Please note that this is not a view issue. When I look at the data in the collection while debugging in the controller, this is what I see. This does not appear to be the only place this is happening. I am seeing something similar with more complicated models - but I thought I'd start with the simplest sample. Thanks!
The problem was caused when I was setting default values on my models. Apparently using static was incorrect. So:
[ReadOnly(true)]
[Display(Name = "Sub total")]
private static decimal _OrderSubTotal = 0;
public decimal OrderSubTotal { get { return _OrderSubTotal; } set { _OrderSubTotal = value; } }
Should be written as
[ReadOnly(true)]
[Display(Name = "Sub total")]
private decimal _OrderSubTotal = 0;
public decimal OrderSubTotal { get { return _OrderSubTotal; } set { _OrderSubTotal = value; } }

Resources