EF Core - detect actual property value changes - entity-framework-core

I'm attempting to detect which fields/properties/columns have changed in DbContext's SaveChanges() method. I'm currently using the following code:
string fields = "";
foreach (var entityProperty in ent.Entity.GetType().GetProperties())
{
var propertyName = entityProperty.Name;
var currentValue = ent.Property(propertyName).CurrentValue;
var originalValue = ent.Property(propertyName).OriginalValue;
if ( currentValue == null && originalValue != null ||
originalValue == null && currentValue != null ||
(currentValue != null && originalValue != null &&
!originalValue.Equals(currentValue))
)
{
fields += propertyName + ", ";
}
}
My code frequently sets the values of columns to their current value so I can't rely on PropertyEntry.IsModified - that seems to get set to true even if you set a field to the same value it already has.
Also, in the above code, originalValue is coming out as the NEW value of the column, so this code isn't working either.
Does anyone know how I can detect which fields/properties/columns have actually had their value changed?

Related

dart null safty issue when try to add value to map element

I am using Dart but i am facing null safty issue with following code
RxMap<Product,int>cartItems=Map<Product,int>().obs;
void updateCart(Product product,String type){
if(type=="plus") {
cartItems.value[product]++;
}
else {
cartItems.value[product]--;
}
}
i got the following error message
the method '+' can't be unconditionally invoked because the receiver can be 'null'
i tried to add null check to the target as following
cartItems.value![product]++;
You can give a default value if null.
cartItems.value[product]??0 +1
Or force assert to non null value like this.It may throw exception if element not present in HashMap
cartItems.value[product]!+1
In your question you are asserting not null for HashMap not the value of the HashMap.
The problem is that cartItems.value is a Map and it's possible that cartItems.value[product] is null. In this case you can't add or remove 1 to null.
So you should do like the following:
if (type == "plus") {
cartItems.value[product] = (cartItems.value[product] ?? 0) + 1;
} else {
cartItems.value[product] = (cartItems.value[product] ?? 0) - 1;
}
Using (cartItems.value[product] ?? 0) you're saying that if cartItems.value[product] is null 0 is used instead.
Also note that in the else clause, when cartItems.value[product] == null, you're trying to remove 1 to something that doesn't exist, so in that case it may be best to throw an exception:
int? currentValue = cartItems.value[product];
if (currentValue == null) {
throw Exception('Trying to remove on a null object');
}
cartItems.value[product] = currentValue - 1;

Function in textFieldDidEndEditing is running when it’s not supposed to run

I've got 5 text fields:
When I type values in any 4 of the text fields, the value should be calculated and it should appear in the 5th text field.
For example, if I enter values in the Interest, Monthly Payment, Future Value and Number of Payments text fields, a value should be calculated and it should appear on the Principal Amount text field.
The calculation takes place when the Keyboard is dismissed (textFieldDidEndEditing).
Here is the code for that:
// When the user has finished typing
func textFieldDidEndEditing(_ textField: UITextField) {
// Principal Amount
let P = Double(principalAmountTextField.text!)
// Interest rate
let r = Double(interestTextField.text!)
// Monthly Payment
let PMT = Double(monthlyPaymentTextField.text!)
// Number of Payments
let t = Double(numOfPaymentsTextField.text!)
// Future Value
let A = Double(futureValueTextField.text!)
// Check if the necessary text fields are filled to find Principal Amount
if futureValueTextField.text != "" && interestTextField.text != "" && numOfPaymentsTextField.text != "" && monthlyPaymentTextField.text != "" {
print(1)
principalAmountTextField.text = String(calculatePrincipalAmountCompound(futureValue: A!, interestRate: r! / 100, payment: PMT!, numOfPayments: t!))
}
// Check if the necessary text fields are filled to find Monthly Payment
if futureValueTextField.text != "" && principalAmountTextField.text != "" && numOfPaymentsTextField.text != "" && interestTextField.text != "" {
print(2)
monthlyPaymentTextField.text = String(calculateMonthlyPaymentCompound(principalAmount: P!, futureValue: A!, numOfPayments: PMT!, interestRate: r! / 100))
}
}
So clearly, if I enter values in the Interest, Monthly Payment, Future Value and Number of Payments text fields, only the first IF condition in the textFieldDidEndEditing method should run, but for some reason, the second IF condition runs too. Why does this happen?
Edit
Thanks to #tomerpacific I was able to make this work. But I still don't know why the above code doesn't work, I just tried running the IF conditions without calling the methods and it works properly:
// Check if the necessary text fields are filled to find Principal Amount
if futureValueTextField.text != "" && interestTextField.text != "" && numOfPaymentsTextField.text != "" {
print(11)
}
// Check if the necessary text fields are filled to find Monthly Payment
if futureValueTextField.text != "" && principalAmountTextField.text != "" && numOfPaymentsTextField.text != "" && interestTextField.text != "" {
print(22)
}
The problem lies with your logic.
Let's break it down to make things clearer.
if futureValueTextField.text != "" && interestTextField.text != "" && numOfPaymentsTextField.text != "" && monthlyPaymentTextField.text != "" {
print(1)
principalAmountTextField.text = String(calculatePrincipalAmountCompound(futureValue: A!, interestRate: r! / 100, payment: PMT!, numOfPayments: t!))
}
When this if condition is true, principalAmountTextField gets a value.
So, after this condition, the following text fields have values:
futureValueTextField
interestTextField
numOfPaymentsTextField
monthlyPaymentTextField
principalAmountTextField
// Check if the necessary text fields are filled to find Monthly Payment
if futureValueTextField.text != "" && principalAmountTextField.text != "" && numOfPaymentsTextField.text != "" && interestTextField.text != "" {
print(2)
monthlyPaymentTextField.text = String(calculateMonthlyPaymentCompound(principalAmount: P!, futureValue: A!, numOfPayments: PMT!, interestRate: r! / 100))
}
Now, since you don't return from your if clauses or don't have an if/else flow, the next if evaluates to true when the following textfields have values:
futureValueTextField
interestTextField
numOfPaymentsTextField
principalAmountTextField
And since you have given principalAmountTextField a value, the second if condition is met and the code runs.

Is there any way to chain optional assignment unwrapping into if conditional in Flutter, the way it is like Swift?

In Swift, there's a simple language feature to chain unwrapping and checking for non null like this:
if let data = functionReturningNullableNumber(), data != 0 { processNum(data) }
if let data = functionReturningNullableString(), data != "" { processStr(data) }
In Flutter, currently I have to do this:
var dataNum = functionReturningNullableNumber();
if (dataNum != null && dataNum != 0) { processNum(dataNum); }
var dataStr = functionReturningNullableString();
if (dataStr != null && dataStr != "") { processStr(dataStr); }
Is it possible to create something similar to the Swift above? Especially the part where I can assign a temporary variable name that will disappear outside of the if scope, so I can reuse the variable name.
Of course I can do this:
if (functionReturningNullableNumber() != null && functionReturningNullableNumber() != 0) { process(functionReturningNullableNumber()); }
But this isn't what I'm searching for.

Preventing repetitive data in date fields ActionsScript2

I have four date fields on a form and I need to alert the user when they have entered repetitive dates. I have already created an array that generates and checks the dates, but throwing the alert is not working for me. This is what I have so far.
else if ((dateRow1.text== dateRow2.text) || (dateRow1.text == dateRow3.text) || (dateRow1.text == dateRow4.text)) {
alert.show("You must have unique dates for each field");
Thanks.
You can check if your text fields are all distinct from each other:
var t:Array = [dateRow1, dateRow2, dateRow3, dateRow4];
var l:Number = t.length;
var i:Number;
var j:Number;
for (i = 0; i < l; i++) {
var ti = t[i]; // dateRow1... dateRow4
for (j in t) {
if (ti != t[j] && ti.text == t[j].text) trace(ti + "==" + t[j]);
}
}

Checking multiple conditions for a string in C#

I want to check multiple conditions in a string in C# but it throws error saying Cannot use && for string or boolean
if ((duStart.Trim() != "" && duStart.Trim() != null) &&(duEnd.Trim() != "" && duEnd.Trim() != null))
{
//do this
}
else
//do that
The code you've given compiles fine. Here's a short but complete program - I've changed the whitespace of your line of code, but that's all:
using System;
class Test
{
static void Main()
{
string duStart = "X";
string duEnd = "X";
if ((duStart.Trim() != "" && duStart.Trim() != null) &&
(duEnd.Trim() != "" && duEnd.Trim() != null))
{
Console.WriteLine("Yes");
}
}
}
Having said that:
If you're going to use the same value (the trimmed version of duStart, for example) multiple times, there seems little point in computing it twice. I'd have used extra local variables (trimmedStart, trimmedEnd) here
Trim never returns null, so those tests are pointless.
Using string.IsNullOrWhitespace is probably a better idea here. Why bother creating strings that you're never going to use?
you can simplify the condition by writing:
if( !string.IsNullOrEmpty(duStart.Trim()) && !string.isNullOrEmpty(duEnd.Trim()) )
{
}
Check for the Null first for duStart and duEnd. Then try Trim the string. Trim cannot be applied on a null value. So, below code block should work for you.
if ((duStart != null && duStart.Trim() != "") && (duEnd != null && duEnd.Trim() != ""))
{
//do this
}
else
{
//do that
}