We have a notmapped conversion field with a kendo control bound to it. When we delete all entries from the control, it posts a null to the controller.
The created model is not running the setter for that field, according to the breakpoints I set in it.
Here's the two fields in question:
[NotMapped]
[Display(Name="Execute Time(s)")]
[DCRequired]
public IList<int> ExecuteTimes {
get
{
return ExecuteHourUTC?.Split(',').Select(s => GetUtcHour(s)).ToList();
}
set
{
if (value != null)
{
// Special code here to ensure the times are numerically in order by local time
// and saved that way for viewing on next load or in the grid.
var values = value.ToList() // convert to List to be sortable/linqable
.OrderBy(x => x) // sort numerically so they are stored in chronological order
.Select(x => new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, x, 0, 0)) // use the integer value to create a DateTime
.Select(d => Core.DateHelper.ToUTC(d, UserTimeZone).Hour); // convert the generated DateTime into a UTC DateTime and return the Hour value
ExecuteHourUTC = string.Join(",", values); // join these Hour (int) values as a CSV
}
}
}
[Display(Name="Execute Times")]
public string ExecuteHourUTC { get; set; }
execute hour utc is bound to the database.
Note: I fixed the problem this was causing (it was leaving the old values in the db field) by bind excluding the db field from the post. I just want to know what the actual reason I'm having this issue is.
I also tried changing the datatype to iList<int?>. That didn't help.
Related
I have the following problem:
I have a Database with a table where I save a String and a Date.
In this table I add an Entry if a certain assignment is printed and when.
On the other hand I have a Database Table from where I get the assignments to do for today.
After inserting the new entry into the Database I select the String with the assignment number and put it into a database,
so I can compare those two lists and check if the list with the printed elements contains all values from the assignments to print today.
How can I achieve this?
I've tried several methods but it always returns false.
The methods I've tried:
if (serial_list_printed.All(x => serial_list.Contains(x)) == true)
{
status = true;
}
else
{
Console.WriteLine("False");
}
2nd Method:
if (serial_list.All(x => serial_list_printed.All(y => y == x)))
{
status = true;
}
else
{
Console.WriteLine("False");
}
How can I check that all the List of Strings with the printed assignment numbers, contains the list of today's assignments?
You can use Except() to get difference between two list and count length of result,
var status = serial_list.Except(serial_list_printed).Any();
if(!status)
Console.WriteLine("False");
i know it is not complicated but i struggle with it.
I have IList<Material> collection
public class Material
{
public string Number { get; set; }
public decimal? Value { get; set; }
}
materials = new List<Material>();
materials.Add(new Material { Number = 111 });
materials.Add(new Material { Number = 222 });
And i have DbSet<Material> collection
with columns Number and ValueColumn
I need to update IList<Material> Value property based on DbSet<Material> collection but with following conditions
Only one query request into database
The returned data from database has to be limited by Number identifier (do not load whole database table into memory)
I tried following (based on my previous question)
Working solution 1, but download whole table into memory (monitored in sql server profiler).
var result = (
from db_m in db.Material
join m in model.Materials
on db_m.Number.ToString() equals m.Number
select new
{
db_m.Number,
db_m.Value
}
).ToList();
model.Materials.ToList().ForEach(m => m.Value= result.SingleOrDefault(db_m => db_m.Number.ToString() == m.Number).Value);
Working solution 2, but it execute query for each item in the collection.
model.Materials.ToList().ForEach(m => m.Value= db.Material.FirstOrDefault(db_m => db_m.Number.ToString() == m.Number).Value);
Incompletely solution, where i tried to use contains method
// I am trying to get new filtered collection from database, which i will iterate after.
var result = db.Material
.Where(x=>
// here is the reasonable error: cannot convert int into Material class, but i do not know how to solve this.
model.Materials.Contains(x.Number)
)
.Select(material => new Material { Number = material.Number.ToString(), Value = material.Value});
Any idea ? For me it is much easier to execute stored procedure with comma separated id values as a parameter and get the data directly, but i want to master linq too.
I'd do something like this without trying to get too cute :
var numbersToFilterby = model.Materials.Select(m => m.Number).ToArray();
...
var result = from db_m in db.Material where numbersToFilterBy.Contains(db_m.Number) select new { ... }
In my project i use kendo grid to show data and in my ActionResult i use this code to get data :
public ActionResult ShowData([DataSourceRequest] DataSourceRequest request, long studentid)
{
IQueryable<Models.Registration.RegistrationModel>
query =
from financeItem in db.RegistrationItems
select new Models.Registration.RegistrationModel
{
RegisterId = financeItem.RegistrationId,
Id = financeItem.Registration.Id,
Date = financeItem.Registration.Date,
StudentName = financeItem.Registration.Student.FirstName + " " + financeItem.Registration.Student.LastName
};
DataSourceResult dsr = query.ToDataSourceResult(request);
return Json(dsr, JsonRequestBehavior.AllowGet);
}
so . I need convert date to local date and I have a problem.
this is my problem :
when I want convert date inside query I get many error that linq2sql can't find converter function. so I change query type from IQueryable to list and try convert . but I get time out error because I've got a lot of records.
after this error I try convert data inside get and set property in viewmodel like this code :
public string DateSs
{
get
{
return DateConvertor(Date.ToString());
}
set { value.ToString(); }
}
and I use this property inside view and show converted data.
Everything works fine so far but when I want use filter part in kendo grid and filter data base on input date I get and error that this filed not exited in query.
so I have a Headache and I don't know what must I do and how can I convert this dame date
For Kendo Grid your Date column is representation for DateSs instead of Date. When it tries to apply filter on Date, it is applying filter on DateSs which doesn't exist in database table and throws error if defined in your query.
I think the solution for that would be to intercept the DataSourceRequest before applying ToDataSourceResult and change the value and filter name accordingly
UPDATE
The filter Kendo Grid sent is in request.Filters but the structure is hierarchical to support multiple Filters in one request. So, first of all you might want to flatten the filter out, you can use this code to that,
public static IEnumerable<IFilterDescriptor> FlattenFilters(this DataSourceRequest request)
{
return request.Filters
.RecursiveSelect(
descriptor => (descriptor as CompositeFilterDescriptor)?.FilterDescriptors ?? Enumerable.Empty<IFilterDescriptor>(),
descriptor => descriptor as FilterDescriptor)
.Where(x => x != null);
}
This function will return an Enumerable of all the filters currently applied. Then you can change the name of filter like this
request.FlattenFilters().Each(x =>
{
FilterDescriptor filter = x as FilterDescriptor;
if (filter != null && filter.Member == "DateSs")
{
filter.Member = "Date";
//Change the filter.Value property according to your case
//i.e. It would be in String and you might want to convert it to date too.
}
});
I have a DB with no constraints (given, not changeable). My model look like
public MyModel
{
public long Id { get; set; }
// Even if database column 'Value' could be NULL,
// the model - from business view - could not.
public long Value { get; set; }
}
My data I'd like to read is
Id Value
1 1
2 2
3 NULL
4 4
When I read with with DBContext.MyModel.ToList() it fails, of course. Is there any possibility to catch the error on 3rd row and return the 3 valid ones?
I don't dependent on EF but I like an automatic mapping between DB an Code.
Update:
It seems I wasn't specific enough. I need the 3 rows AS WELL AS a notification for the error.
Additional I've created a simple case for demo. In real life I have around 800 tables with up to 250 columns. I can't catch anything by model modification like dates out of range, missing relationships and other stuff.
What I really need is a try..catch for every row or an event on row reading failure, something like this.
Ok, solved. Not very elegant, but functional.
var query = _DBContext
.Database
.SqlQuery<MyModel>("SELECT * FROM MyModel");
var result = new List<MyModel>();
var enumerator = query.GetEnumerator();
while (true)
{
try
{
var success = enumerator.MoveNext();
if (!success)
break;
var model = enumerator.Current;
result.Add(model);
}
catch (Exception ex)
{
}
}
return result;
You need to use nullable type
public MyModel
{
public long Id { get; set; }
// Even if database column 'Value' could be NULL,
// the model - from business view - could not.
public long? Value { get; set; }
}
And also, in your select query, you should exlude Value = null
var myModel = models.Where(x => x.Value != null);
Hope it helps.
I'm not entirely sure I understand what you're trying to do, but if you want to get a reflection of what's in the table, then why not make your model match the query? If Value can be NULL, then make Value nullable (i.e. define it as long?).
That way, you can simply do:
var records = DbContext.MyModel.ToList();
If you then want to filter out the NULLs, you can do:
records.Where(r => r.Value.HasValue)
And if you want the ones with NULLs you can do:
records.Where(r => !r.Value.HasValue)
Or if you want to know whether any row had a NULL you could do:
records.Any(r => !r.Value.HasValue)
Use the following code:
var list = from m in DBContext.MyModel
where (m != null)
select m;
And then just convert var list to a List of your choosing.
Edit 1
var myModel = models.Where(x => x.Value != null).ToList();
As kienct89 suggested might also work.
Edit 2
There are multiple options for "catching" the error
If you want to throw an exception just use this:
if(myList.Count() < DBContext.MyModel.Count()){
Exception myException = new Exception("Not all items ware correctly loaded");
throw myException;
}
OR create a seperate array with the faulty ones:
var faultyList = from m in DBContext.MyModel
where (m == null)
select m;
Or:
var faultyList= models.Where(x => x.Value == null).ToList();
See i have this following code below, at line no.9 i'm calculating some dates to move forward, so im using AddDays method but in return i'm getting all dates same for all rows.
If i do AddDays(6) like this then it is returning correctly by moving all dates by 6 days.
How should i do it for adding days according to my logic at this point.
[DataContract]
public class JQGridRow
{
[DataMember]
public long id;
[DataMember]
public object[] cell;
}
var sortedItems = invBatch.ListOfItems.OrderBy(i => i.RunDateIndex);//This will return IEnumerable<Class> List
DateTime startDate = DateTime.Parse(lblStartDate.Text);
JQGrid.JQGridRow[] rowData = (
from i in sortedItems
select new JQGrid.JQGridRow() {
id = i.ID,
cell = new string[] {
i.ID.ToString(),
i.Status.ToString(),
i.StatusTitle,
i.RunDate.AddDays((startDate.Subtract(i.RunDate)).Days+1).ToString(Utility.DATE_FORMAT),
//Here in above line the array returning same values for all columns of this row
i.StartTimeString,
i.EndTimeString,
i.EndTime.ToString(),
}}).ToArray();
The dates are all same and equal the next day after startDate because you calculate them as such.
i.RunDate.AddDays((startDate.Subtract(i.RunDate)).Days+1)
Rounding to whole day, you compute RunDate+(startDate-RunDate+1) = startDate + 1. i.RunDate does not matter.