proper date and time management entity and html helpers - entity-framework-core

I'm trying to bind 2 different fields in 2 different classes
one is a date
I have to force "value", for some reason, the binding works for post, but not at get
#Html.EditorFor(model => model.FilterStartDate, new { type = "date", #class="form-control", #Value = (Model.FilterStartDate == null ? "" : Model.FilterStartDate.Value.ToString("yyyy-MM-dd")) })
Is there a way to do it better ? also, why does the class attribute is ignored ?
Also, why do I still have the time ? i'd like to just be about dates

Related

Can I get a field from a list of maps using a variable name instead of a specific field name

I have a list of maps (bText) and the map of field names include (kjvtext, nasbtext, esvtext) string fields.
I have another preferences variable: String bVersion = "esvtext";
I want to access the map field bText[index].esvtext when the bVersion field contains "esvtext" and field bText[index].nasbtext when the bVersion field contains "nasbtext".
I've tried several combinations of code such as:
Text(bText[index].bVersion)
Text(bText[index].[bVersion])
Text(bText[index]."$bVersion")...
I've finally resorted to:
xText = (bVersion == "kjvtext")
? verselist[index].kjvtext
: (bVersion == "nasbtext")
? verselist[index].nasbtext
: (bVersion == "esvtext")
? verselist[index].esvtext
: "bVersion version error\n",
Seems like there would be a simpler way to code this?
Any thoughts? Thanks in advance!

How to concatenate column data and return in linq select

I have a table where it has the columns like IsAgreed, IsOther, IsEquipped. On the UI I am showing 3 check boxes where one can select single or multiple check boxes. The data is getting saved to db as expected. Now I am trying to select the data in entity framework as follows
from tbl context.TableNames select new {
Conitions= tbl.IsOther ? tbl.OtherText : tbl.IsAgreed ? "Agreed :
tbl.IsEquipped? "Equipped" : "" }
Which is giving only one selection when the multiple selection are made. I would like to concat and result the data so that it can be
OtherText, Agreed, Equipped
OtherText, Equipped
Agreed, Equipped
Is it possible to concatenate and give the expected output
You can create an array of strings based on conditions, after it can be formatted as desired. Please pay attention to the comment i wrote in the code sample.
var conditions = context.TableNames.Select(tbl => new
{
tbl.IsOther,
tbl.IsAgreed,
tbl.IsEquipped
})
.AsEnumerable() //Should be used with caution. Because it will load each record to memory. It also switches "LINQ to Entities" to "LINQ to Objects", so we can use string.Join.
.Select(c => new
{
Conditions = string.Join(", ", new string[] { c.IsOther ? "OtherText" : "", c.IsAgreed ? "Agreed" : "", c.IsEquipped ? "Equipped" : "" }.Where(s => !string.IsNullOrEmpty(s)))
});

GroupJoin: exception thrown: System.InvalidOperationException

I'm trying to write a query to get all restaurant tables if exists or not a opened sale on it.
if a sale exists on a table I want to get the sum and couple details.that is my code:
db.SALETABLES
.GroupJoin(
db.SALES.Where(c => c.CLOSEDTIME == null),
t => t.ID,
sa => sa.ID_TABLE,
(ta, s) => new
{
ta.ID,
ta.DESCRIPTION,
NR_SALE = s.Any() ? s.First().NR_SALE : 0,
IDSALE = s.Any() ? s.First().ID : 0,
IDUSER = s.Any() ? s.First().IDUSER : 0,
USERNAME = s.Any() ? s.First().USERS.USERNAME :"" ,
SALESUM = s.Any() ? s.First().SALES_DETAIL.Sum(p => p.PRICE * p.CANT) : 0
}
but got this error:
Exception thrown: 'System.InvalidOperationException' in
System.Private.CoreLib.dll
thanks for any help
You don't specify the exception, but I assume it's about client-side evaluation (CSE), and you configured EF to throw an exception when it occurs.
It may be First() that triggers CSE, or GroupJoin. The former can easily be fixed by using FirstOrDefault(). The GroupJoin has more to it.
In many cases it isn't necessary to use GroupJoin at all, of Join, for that matter. Usually, manually coded joins can and should be replaced by navigation properties. That doesn't only make the code better readable, but also avoids a couple of issues EF 2.x has with GroupJoin.
Your SaleTable class (I'm not gonna follow your database-driven names) should have a property Sales:
public ICollection<Sale> Sales { get; set; }
And if you like, Sale could have the inverse navigation property:
public SaleTable SaleTable { get; set; }
Configured as
modelBuilder.Entity<SaleTable>()
.HasMany(e => e.Sales)
.WithOne(e => e.SaleTable)
.HasForeignKey(e => e.SaleTableId) // map this to ID_TABLE
.IsRequired();
Now using a table's Sales property will have the same effect as GroupJoin —a unique key, here a SaleTable, with an owned collection— but without the issues.
The next improvement is to simplify the query. In two ways. 1. You repeatedly access the first Sale, so use the let statement. 2. The query is translated into SQL, so don't worry about null references, but do prepare for null values. The improved query will clarify what I mean.
var query = from st in db.SaleTables
let firstSale = st.Sales.FirstOrDefault()
select new
{
st.ID,
NrSale = (int?)firstSale.NrSale ?? 0,
IdSale = (int?)firstSale.ID ?? 0,
...
SalesSum = (int?)firstSale.SalesDetails.Sum(p => p.Price * p.Cant) ?? 0
}
Using NrSale = firstSale.NrSale, would throw an exception for SaleTables without Sales (Nullable object must have a value).
Since the exception is by the EF Core infrastructure, apparently you are hitting current EF Core implementation bug.
But you can help EF Core query translator (thus avoiding their bugs caused by missing use cases) by following some rules when writing your LINQ to Entities queries. These rules will also eliminate in most of the cases the client evaluation of the query (or exception in EF Core 3.0+).
One of the rules which is the origin of issues with this specific query is - never use First. The LINQ to Objects behavior of First is to throw exception if the set is empty. This is not natural for SQL which naturally supports and returns NULL even for values which normally do not allow NULL. In order to emulate the LINQ to Objects behavior, EF Core has to evaluate First() client side, which is not good even if it works. Instead, use FirstOrDefault() which has the same semantics as SQL, hence is translated.
To recap, use FirstOrDefault() when you need the result to be a single "object" or null, or Take(1) when you want the result to be a set with 0 or one elements.
In this particular case, it's better to incorporate the 0 or 1 related SALE rule directly into the join subquery, by removing the GroupJoin and replacing it with SelectMany with correlated Where. And the Any() checks are replaced with != null checks.
With that said, the modified working and fully server translated query looks like this:
var query = db.SALETABLES
.SelectMany(ta => db.SALES
.Where(s => ta.ID == s.ID_TABLE && s.CLOSEDTIME == null).Take(1), // <--
(ta, s) => new
{
ta.ID,
ta.DESCRIPTION,
NR_SALE = s != null ? s.NR_SALE : 0,
IDSALE = s != null ? s.ID : 0,
IDUSER = s != null ? s.IDUSER : 0,
USERNAME = s != null ? s.USERS.USERNAME : "",
SALESUM = s != null ? s.SALES_DETAIL.Sum(p => p.PRICE * p.CANT) : 0
});

How to define and access local variable in Typoscript 2 (Neos)?

I have created a custom NodeType "Events" with a custom TS2 file in Neos, but I guess it is more a general question about Typoscript 2.
prototype(Some.Namespace:Events) < prototype(TYPO3.Neos:Document) {
...
sortOrder = ${request.arguments.sortOrder == 'asc' ? 'asc' : 'desc'}
otherVariable = ${sortOrder}
...
}
Of course this is simplified to focus on the issue:
I want to assign the value of the variable sortOrder (which is "asc" or "desc") to another variable named otherVariable.
How can I do that? I cannot access the value using ${sortOrder}, which returns always NULL.
All you need to do is add this as below and {otherVariable} in your fluid template will work. Flush cache in case you sill have NULL.
sortOrder = ${request.arguments.sortOrder == 'asc' ? 'asc' : 'desc'}
otherVariable = ${this.sortOrder}

Webform form alter date hide day

I'm relatively new to Drupal 7 and I'm trying to create a custom webform. My goal is to add a date (provided by the date module) field with out the day option. So it displays on month and year hiding the day option.
I have managed to achieve this but only by recreating the wholedate field as a custom field but I wanted to know if it was possible to customize the date field provided by the date module.
Below is a screen shot of my form:
How I create my custom date field:
function my_webform_form_alter(&$form, &$form_state) {
if (isset($form['#node']->webform) && $form['#node']->uuid == '00b20537-d5ce-45c2-af37-150c9e73b96d') {
//$form['submitted']['date']['#type'] = 'hidden';
$form['ggg'] = array(
'#type' => 'date_select',
'#title' => 'Date',
'#date_format' => 'm/Y',
'#default_value' => date('Y-m-d')
);
}
}
I have tried other methods on hiding the field components but nothing seem to work so far. I was wondering if I needed to implement a hook different from the alter hook (the one being used).
Any suggestions on how to achieve this?
A possible solution would be to transform the day field of the date component to a hidden field instead of the select field type. That can be achieved by adding a #process callback for that field and altering the data.
function YOURMODULE_form_alter(&$form, &$form_state, $form_id)
{
// Your logic here depending which form to alter
// ...
// Add #process for the component with key name 'date'
$form['submitted']['date']['#process'][] = 'YOURMODULE_process_date';
}
function YOURMODULE_process_date(&$element)
{
// change type to hidden
$element['day']['#type'] = 'hidden';
// set value to first day of the month
$element['day']['#value'] = '1';
return $element;
}
Webform now allows hiding the day, month or year of a date. See this issue for details.