consume int result returned from stored procedure in MVC4 - entity-framework

I have created stored procedure like this:
ALTER procedure [dbo].[takeOrder]
(
#id int = 0,
#userid int = 0,
#diningid int,
#amount float
)
as
begin
declare #countt as int
select #countt = COUNT(*)
from Order_master
where dining_Id = #diningid and isActive = 1
if #countt <> 0
begin
update Order_master
set amount = #amount
where dining_Id = #diningid and isActive = 1;
end
else
begin
insert into Order_master(userid, dining_Id, amount, [date], isActive)
values (#userid, #diningid, #amount, GETDATE(), 1)
end
--select amount from Order_master where dining_Id=#diningid and isActive=1
select oid
from Order_master
where dining_Id = #diningid and isActive = 1
end
In controller I am trying to get return result as mention below:
[HttpPost]
public ActionResult takeOrder(Order_master order,List<Menu_info> menu)
{
String msg = "";
int oid;
if (ModelState.IsValid)
{
try
{
Order_master objOreder = new Order_master
{
amount = order.amount,
isActive = 1,
date = order.date,
dining_Id = order.dining_Id,
userId = order.userId
};
object orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount);
oid = (int)orderId;
msg = "success..!!";
}
catch (Exception ex)
{
msg = "error...";
}
}
else
{
msg = "please provide info";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else
{
return View();
}
}
But it returns an exception
Cannot convert type 'System.Data.Objects.ObjectResult' to 'int'
I am not able to get single return value from stored procedure.
Hope I get the right solution.

object orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount);
oid = (int)orderId;
Try this conversion method.
oid = Convert.ToInt32(orderId);

You can use like
public int InsertWebProperty(int orgid, int? userid, string address, string property_Id, string latitude, string longitude, int? compamyid)
{
return Convert.ToInt32((db.InsertWebProperty(orgid, userid, address, property_Id, latitude, longitude, 0)).FirstOrDefault().recidentity.Value);
}
Please let me know if it not worked for you..
Thanks

db.TakeOrder().FirstOrDefault().ToString() = One value returned as a string
db.TakeOrder().FirstOrDefault().ToList() = Row returned as a list.

Create view as
CREATE VIEW [dbo].[vScalar]
AS
SELECT '' AS Value
In Stored Procedure return
SELECT CAST(orderId AS VARCHAR(10)) AS value
In Entity Framework, set function return use entity vScalar
In code
vScalar orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount).FirstOrDefault;
oid = (int)orderId.value;

Related

Postgres function is not working/calling in hosted web project

I have created an ASP.Net Core Web App (MVC) Project which in turns call Web Api for calling the database for getting the values and posting the values. The database used is Postgres. I have written a Postgres function to populate values for a report Day Book. When I run the project through visual studio it works fine. Then I have hosted the project. When I login through hosted ip address and calling the report function returns no values and the reports showing no values.
The Postgres function is given below
CREATE OR REPLACE FUNCTION public.day_book(
d1 date,
d2 date,
cid integer)
RETURNS TABLE(roworder integer, guid uuid, tbl1 text, date1 timestamp without time zone, credit real, debit real, description1 text, credit1 real, debit1 real)
LANGUAGE 'plpgsql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
BEGIN
RETURN QUERY
SELECT db1."roworder",db1."guid",db1."tbl1",db1."date1",db1."credit",db1."debit",
db1."description1",db1."credit1",db1."debit1"
from "tbldaybook1" as db1 order by db1."date1",db1."roworder";
END;
$BODY$;
The MVC controller method that calls the API controller method is given below
public async Task<JsonResult> GetDayBook(DateTime FromDate, DateTime ToDate)
{
ClaimsPrincipal currentUser = this.User;
var currentUserId = Convert.ToInt32(currentUser.FindFirst("UserId").Value);
var ChurchId = Convert.ToInt32(currentUser.FindFirst("ChurchId").Value);
var Role = currentUser.FindFirst(ClaimTypes.Role).Value;
var isSuperAdmin = Convert.ToBoolean(currentUser.FindFirst("IsSuperAdmin").Value);
var d11 = FromDate.ToString("dd-MM-yyyy");
var d22 = ToDate.ToString("dd-MM-yyyy");
int cid = ChurchId;
List<RptDayBook> daybook = new List<RptDayBook>();
HttpClient client = api.Initial();
HttpResponseMessage responseTask = await client.GetAsync("reports/GetDayBook/" + d11 + "/" + d22 + "/" + cid);
if (responseTask.IsSuccessStatusCode)
{
var readTask = responseTask.Content.ReadAsStringAsync().Result;
daybook = JsonConvert.DeserializeObject<List<RptDayBook>>(readTask);
}
return Json(daybook);
}
The below API method connects to the Postgres database and call the function
[HttpGet("GetDayBook/{d11}/{d22}/{cid}")]
public IEnumerable<RptDayBook> GetDayBook(string d11, string d22, int cid)
{
using (var command = db.Database.GetDbConnection().CreateCommand())
{
DateTime d1 = Convert.ToDateTime(d11);
DateTime d2 = Convert.ToDateTime(d22).AddDays(1);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "day_book";
command.Parameters.Add(new Npgsql.NpgsqlParameter("d1", NpgsqlTypes.NpgsqlDbType.Date)
{ Value = d1 });
command.Parameters.Add(new Npgsql.NpgsqlParameter("d2", NpgsqlTypes.NpgsqlDbType.Date)
{ Value = d2 });
command.Parameters.Add(new Npgsql.NpgsqlParameter("cid", NpgsqlTypes.NpgsqlDbType.Integer)
{ Value = cid });
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
List<object[]> result = new List<object[]>();
var res = command.ExecuteReader();
if (res.HasRows)
{
while (res.Read())
{
var values = new object[res.FieldCount];
for (int i = 0; i < res.FieldCount; i++)
{
if (i == 4 || i == 5 || i == 7 || i == 8)
{
values[i] = res[i] == DBNull.Value ? 0 : Convert.ToDouble(res[i]);
}
else
{
values[i] = res[i];
}
}
result.Add(values);
}
}
List<RptDayBook> rpt = new List<RptDayBook>();
foreach (var item in result)
{
RptDayBook rptDayBook = new RptDayBook();
rptDayBook.roworder = (int)item[0];
rptDayBook.GUID = (Guid)item[1];
rptDayBook.tbl1 = (string)item[2];
rptDayBook.date1 = (DateTime)item[3];
rptDayBook.credit = item[4] == DBNull.Value ? 0 : Convert.ToDouble(item[4]);
rptDayBook.debit = item[5] == DBNull.Value ? 0 : Convert.ToDouble(item[5]);
rptDayBook.Description1 = (string)item[6];
rptDayBook.credit1 = item[7] == DBNull.Value ? 0 : Convert.ToDouble(item[7]);
rptDayBook.debit1 = item[8] == DBNull.Value ? 0 : Convert.ToDouble(item[8]);
rpt.Add(rptDayBook);
}
return rpt;
}
}
What will be the issue? Is it either the function is not calling or function can't return values?
It is the issue while converting the datetime in the API.
Change the code from
DateTime d1 = Convert.ToDateTime(d11);
to
DateTime d1 = DateTime.ParseExact(d11, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Also do the same in the next line also.

C# ExecuteReaderAsync Sporadic Issue

I have a method that is getting a list of users. There is a store procedure that is expected either a username or null. It returns one or more users based on the parameter. It works fine most of the time, but I notice there are times it does not return any result even though I am passing the same exact parameter. I put a break point in the Execute Reader Async, and the line immediately following it. When the issue occurs, it reaches the first break point but not the second one. It does not throw an exception or prevent me from making another call. I can make the next call, and it will return the result as expected. I would appreciate some suggestions as to what may cause this issue?
public async Task<List<User>> GetUsers(string username, int accountType = 1)
{
List<User> users = null;
parameters = new List<SqlParameter>{
new SqlParameter{
DbType = DbType.String,
ParameterName = "#userName",
Value = username.NotEmpty() ? username : (object) DBNull.Value
},
new SqlParameter{
DbType = DbType.Int32,
ParameterName = "#accountType",
Value = accountType
}
};
try
{
using (SqlConnection con = new SqlConnection(conStr))
{
await con.OpenAsync();
using (SqlCommand cmd = new SqlCommand("spGetUsers", con))
{
cmd.Parameters.AddRange(parameters.ToArray());
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = await cmd.ExecuteReaderAsync()
if (dr.HasRecord())
{
while (await dr.ReadAsync())
{
User user = new User();
user.FirstName = dr["firstName"].ToString();
user.LastName = dr["lastName"].ToString();
user.DateRegister = Convert.ToDateTime(dr["DateRegister"].ToString());
user.Active = Convert.ToBoolean(dr["Active"].ToString());
if(users == null)
{
users = new List<User>();
}
users.Add(user);
}
}
}
}
}
catch (Exception ex)
{
Util.LogError(ex.ToString());
users = null;
}
return users;
}
Update:
Yes, the error is being logged. Also, I added a breakpoint in the catch statement in case an error is thrown.
Here is the query that is used to create that store procedure:
IF EXISTS (SELECT 1 FROM SYS.objects WHERE object_id = OBJECT_ID('spGetUsers') AND TYPE IN (N'PC', N'P'))
DROP PROCEDURE spGetUsers
GO
CREATE PROCEDURE spGetUsers
#userName nvarchar(50),
#accountType int = 1
AS
BEGIN
SELECT U.firstName, U.lastName, U.DateRegister, A.Active
FROM [User] U
inner join UserAccount UA
on U.Id = UA.userid
inner join Account A
on A.Id = UA.accountId
WHERE U.Id > 0
AND UA.Id > 0
AND A.Id > 0
AND UA.AccountType IN (#accountType )
and (A.UserName in (#userName) or #userName IS NULL)
END
Extension Method to check if SQL DataReader has record
public static bool HasRecord(this System.Data.SqlClient.SqlDataReader dr)
{
if (dr != null && dr.HasRows)
{
return true;
}
return false;
}

Using Dapper and Postgresql - citext data type

I'm not sure if there is a way to support this, but I'm having trouble getting Dapper to map string parameter values to the Postgresql citext data type as it seems to be using the text type.
In particular, I'm trying to call a function that takes in citext parameters - the error I get back is:
var c = ConnectionManager<T>.Open();
string sql = #"select * from ""dbo"".""MyFunction""(#schemaName, #tableName);";
var param = new
{
schemaName = schema,
tableName = table
};
string insecureSalt = c.QueryMultiple(sql, param).Read<string>().FirstOrDefault();
ConnectionManager<T>.Close(c);
Error: Npgsql.PostgresException: 42883: function dbo.MyFunction(text, text) does not exist.
The signature that would match is function dbo.MyFunction(citext, citext) so clearly it can't find it using the default mapping.
According to Npgsql - http://www.npgsql.org/doc/types.html I need to be able to specify NpgsqlDbType.Citext as the type but I can't find a way to do this using Dapper.
Solved thanks to answer from Shay, complete solution here:
var c = ConnectionManager<T>.Open();
string sql = #"select * from ""dbo"".""MyFunction""(#schemaName, #tableName);";
var param = new
{
schemaName = new CitextParameter(schema),
tableName = new CitextParameter(table)
};
string insecureSalt = c.QueryMultiple(sql, param).Read<string>().FirstOrDefault();
ConnectionManager<T>.Close(c);
public class CitextParameter : SqlMapper.ICustomQueryParameter
{
readonly string _value;
public CitextParameter(string value)
{
_value = value;
}
public void AddParameter(IDbCommand command, string name)
{
command.Parameters.Add(new NpgsqlParameter
{
ParameterName = name,
NpgsqlDbType = NpgsqlDbType.Citext,
Value = _value
});
}
}
You probably need to create create a CitextParameter which extends ICustomQueryParameter. This API allows you to pass an arbitrary DbParameter instance to Dapper - in this case it would be an instance of NpgsqlParameter with its NpgsqlDbType set to Citext.
Something like this should work:
class CitextParameter : SqlMapper.ICustomQueryParameter
{
readonly string _value;
public CitextParameter(string value)
{
_value = value;
}
public void AddParameter(IDbCommand command, string name)
{
command.Parameters.Add(new NpgsqlParameter
{
ParameterName = name,
NpgsqlDbType = NpgsqlDbType.Citext,
Value = _value
});
}
}
When you write the SQL query, you can cast the parameter value like cast(#param as citext).
in my case below worked correctly. (usr is a class object)
string sql = "select * from users where user_name = cast(#user_name as citext) and password = #password;";
IEnumerable<users> u = cnn.Query<users>(sql, usr);
In your case, you can change the query like below and see if that works
string sql = #"select * from ""dbo"".""MyFunction""(cast(#schemaName as citext), cast(#tableName as citext));";

Postgresql update - Using ArrayList

I am getting an exception on update of postgres:
org.postgresql.util.PSQLException: Can't infer the SQL type...
Here is the code where in I build the sql statement dynamically and append the params:
public Boolean update(UserData usrData){
String sqlUpdateUser = "UPDATE \"USER\" ";
String sqlSetValues = "SET";
String sqlCondition = "Where \"USER_ID\" = ? ";
List<Object> params = new ArrayList<Object>();
List<Integer> types = new ArrayList<Integer>();
if(usrData.getFirstName() != null){
sqlSetValues = sqlSetValues.concat(" \"FIRST_NAME\" = ? ").concat(", ");
params.add(usrData.getFirstName());
types.add(Types.VARCHAR);
}
if(usrData.getMiddleName() != null){
sqlSetValues = sqlSetValues.concat("\"MIDDLE_NAME\" = ? ");
params.add(usrData.getMiddleName());
types.add(Types.VARCHAR);
}
params.add(usrData.getUserId());
types.add(Types.BIGINT);
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
sqlUpdateUser = sqlUpdateUser.concat(sqlSetValues).concat(sqlCondition);
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, updateParams, paramTypes);
if(rowsAffected > 0){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
And table schema for the USER table is:
"FIRST_NAME" character varying(50),
"MIDDLE_NAME" character varying(50),
If I do an update statically without using the collection, but by using Array, I see no issue.
Code snipped using arrays:
Object[] param = { usrData.getFirstName(), usrData.getMiddleName(), usrData.getUserId() };
int[] type = { Types.VARCHAR, Types.VARCHAR, Types.BIGINT };
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, param, type);
Am I missing something?
Thanks
K
Move these lines
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
beneath
params.add(usrData.getUserId());
types.add(Types.INTEGER);
In your case you are missing to add usrData.getUserId() in updateParams.

Convert datetime to a formatted string inside a LINQ-to-entities query

How can I convert DateTime into a formatted string?
This is the line in the following query that needs help:
StartDate = string.Format("{0:dd.MM.yy}", p.StartDate)
The whole query:
var offer = (from p in dc.CustomerOffer
join q in dc.OffersInBranch
on p.ID equals q.OfferID
where q.BranchID == singleLoc.LocationID
let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
orderby value descending
select new Offer()
{
Title = p.OfferTitle,
Description = p.Description,
BestOffer = value,
ID = p.ID,
LocationID = q.BranchID,
LocationName = q.CustomerBranch.BranchName,
OriginalPrice = SqlFunctions.StringConvert((decimal)p.OriginalPrice),
NewPrice = SqlFunctions.StringConvert((decimal)p.NewPrice),
StartDate = string.Format("{0:dd.MM.yy}", p.StartDate)
}).First();
I get the following error message:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
Another option is using SqlFunctions.DateName, your code will be like this:
var offer = (from p in dc.CustomerOffer
join q in dc.OffersInBranch
on p.ID equals q.OfferID
where q.BranchID == singleLoc.LocationID
let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
orderby value descending
select new
{
Title = p.OfferTitle,
Description = p.Description,
BestOffer = value,
ID = p.ID,
LocationID = q.BranchID,
LocationName = q.CustomerBranch.BranchName,
OriginalPrice = SqlFunctions.StringConvert((decimal)p.OriginalPrice),
NewPrice = SqlFunctions.StringConvert((decimal)p.NewPrice),
StartDate = SqlFunctions.DateName("day", p.StartDate) + "/" + SqlFunctions.DateName("month", p.StartDate) + "/" + SqlFunctions.DateName("year", p.StartDate)
})
I found it useful if you don't want to add an extra select new block.
EDIT: Now that I understand the question, I'm giving it another shot :)
var offer = (from p in dc.CustomerOffer
join q in dc.OffersInBranch
on p.ID equals q.OfferID
where q.BranchID == singleLoc.LocationID
let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
orderby value descending
select new
{
Title = p.OfferTitle,
Description = p.Description,
BestOffer=value,
ID=p.ID,
LocationID=q.BranchID,
LocationName=q.CustomerBranch.BranchName,
OriginalPrice=SqlFunctions.StringConvert((decimal)p.OriginalPrice),
NewPrice=SqlFunctions.StringConvert((decimal)p.NewPrice),
StartDate=p.StartDate
})
.ToList()
.Select(x => new Offer()
{
Title = x.OfferTitle,
Description = x.Description,
BestOffer=value,
ID=x.ID,
LocationID=x.BranchID,
LocationName=x.CustomerBranch.BranchName,
OriginalPrice=x.OriginalPrice,
NewPrice=x.NewPrice,
StartDate=x.StartDate.ToString("dd.MM.yy")
}).First();
I know it's a bit long, but that's the problem with Linq To SQL.
When you use linq, the database call isn't executed until you use something such as ToList() or First() that results in actual objects. Once that SQL call is executed by the first .First() call, you're now working with .NET types, and can use DateTime stuff.
I ended up using the sql function FORMAT; here's a simplified version of this implementation:
https://weblogs.asp.net/ricardoperes/registering-sql-server-built-in-functions-to-entity-framework-code-first
First you need to define the function in EF:
public class FormatFunctionConvention : IStoreModelConvention<EdmModel>
{
public void Apply(EdmModel item, DbModel model)
{
var payload = new EdmFunctionPayload
{
StoreFunctionName = "FORMAT",
Parameters = new[] {
FunctionParameter.Create("value", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.DateTime), ParameterMode.In),
FunctionParameter.Create("format", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String), ParameterMode.In)
},
ReturnParameters = new[] {
FunctionParameter.Create("result", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String), ParameterMode.ReturnValue)
},
Schema = "dbo",
IsBuiltIn = true
};
item.AddItem(EdmFunction.Create("FORMAT", "CodeFirstDatabaseSchema", item.DataSpace, payload, null));
}
}
Then define it as C# methods:
public static class SqlFunctions
{
[DbFunction("CodeFirstDatabaseSchema", "FORMAT")]
public static String Format(this DateTime value, string format)
{
return value.ToString(format);
}
[DbFunction("CodeFirstDatabaseSchema", "FORMAT")]
public static String Format(this DateTime? value, string format)
{
return value?.ToString(format);
}
}
Register it in your DbContext:
public class SqlDb : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Add(new FormatFunctionConvention());
}
}
And finally, you can call it like so:
var x = db.MyItems.Select(i => new { FormattedDate = SqlFunctions.Format(i.MyDate, "MM/dd/yyyy") }).ToArray();
That is what we did, we added a new function to the class and we query the date as normal in the query:
[ComplexType]
public class Offer
{
public DateTime StartDate
{
get;
set;
}
public String Title
{
get;
set;
}
/*Other fields*/
.
.
.
public string FormattedDate(string format)
{
return Date.ToString(format);
}
}
var offer = (from p in dc.CustomerOffer
join q in dc.OffersInBranch
on p.ID equals q.OfferID
where q.BranchID == singleLoc.LocationID
let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
orderby value descending
select new Offer()
{
Title = p.OfferTitle,
Description = p.Description,
BestOffer = value,
ID = p.ID,
LocationID = q.BranchID,
LocationName = q.CustomerBranch.BranchName,
OriginalPrice = SqlFunctions.StringConvert((decimal)p.OriginalPrice),
NewPrice = SqlFunctions.StringConvert((decimal)p.NewPrice),
StartDate = p.StartDate
}).First();
Then you can just call the FormattedDate field passing the desired format.
edit1.Text = offer.FormattedDate("dd.MM.yy");
Or can can define it as a field with just the getter:
public string FormattedDate
{
get { return Date.ToString("dd.MM.yy") };
}
edit1.Text = offer.FormattedDate;
In case you class is an Entity, you need to declare a new partial of that class and add the field.
Hope this help someone.
In vb (valid to c# too changing syntax):
Imports System.Data.Entity
...
query.Select(Function(x) New MyObject With {
...
.DateString = DbFunctions.Right("00" & x.DateField.Day, 2) & "/" & DbFunctions.Right("00" & x.DateField.Month, 2) & "/" & x.DateField.Year
...
}).ToList()
Note: ToList(), ToEnumerable() are not the way because its executes a query, the user wants linq to sql..
The easiest and most efficient way I have found to do string formats on numeric or datetime objects is by using string interpolation. It will bring back the actual DateTime/int/float/double/etc.. objects in the SQL query, and then client side it will do the string format during projection. I modified your query below, note how OriginalPrice, NewPrice, and StartDate are converted:
var offer = (from p in dc.CustomerOffer
join q in dc.OffersInBranch
on p.ID equals q.OfferID
where q.BranchID == singleLoc.LocationID
let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
orderby value descending
select new Offer()
{
Title = p.OfferTitle,
Description = p.Description,
BestOffer = value,
ID = p.ID,
LocationID = q.BranchID,
LocationName = q.CustomerBranch.BranchName,
OriginalPrice = $"{p.OriginalPrice:C2}",
NewPrice = $"{p.NewPrice:C2}",
StartDate = $"{p.StartDate:dd.MM.yy}"
}).First();
if it's a datetime you need to use the .ToShortDateString(). But you also need to declare it AsEnumerable().
var offer = (from p in dc.CustomerOffer.AsEnumerable()
join q in dc.OffersInBranch
on p.ID equals q.OfferID
where q.BranchID == singleLoc.LocationID
let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
orderby value descending
select new
{
Title = p.OfferTitle,
Description = p.Description,
BestOffer=value,
ID=p.ID,
LocationID=q.BranchID,
LocationName=q.CustomerBranch.BranchName,
OriginalPrice=SqlFunctions.StringConvert((decimal)p.OriginalPrice),
NewPrice=SqlFunctions.StringConvert((decimal)p.NewPrice),
StartDate=p.StartDate
})
.ToList()
.Select(x => new Offer()
{
Title = x.OfferTitle,
Description = x.Description,
BestOffer=value,
ID=x.ID,
LocationID=x.BranchID,
LocationName=x.CustomerBranch.BranchName,
OriginalPrice=x.OriginalPrice,
NewPrice=x.NewPrice,
StartDate=x.StartDate.ToShortDateString()
}).First();