EF 5 (Code First) AddOrUpdate duplicates nested data [duplicate] - entity-framework-5

This is the code in the Seed method:
var city = new City { Name = "A" };
var nh = new List<Neigh>
{
new Neigh { City = city, Name = "N1" },
new Neigh { City = city, Name = "N2" },
new Neigh { City = city, Name = "N3" },
//new Neigh { City = city, Name = "N4" },
};
context.Neighs.AddOrUpdate(
p => p.Name,
nh.ToArray()
);
After running update-database everything works as expected. I can run it multiple times without problem. However if at some point I uncomment the fourth neighborhood and run update-database again I end up with two records with city "A" and N4 is pointing to that city, while the rest point to the original city.
How do I prevent the inserting of a duplicate city if the list gets updated?

You must start the script by checking whether the city already exists:
var city = context.Cities.FirstOrDefault(c => c.Name == "A")
?? new City { Name = "A" };

Related

PostgreSQL query returning values that are not in my database

I am working on constructing a query to my database to return some data. Here is the link to a previous post describing my intentions Finding database data that best fits user variable responses. I want to return all of the columns for each data object, however the id that is returned is not correct and an additional VALUE field is being returned.
My database is set up like this
venues
id name parking decorations hotel
1 park 1 2 1
2 beach 1 2 2
3 theater 2 2 2
4 yard 2 1 1
and an enum table
id value
1 TRUE
2 FALSE
3 MAYBE
I am building a query on my backend as follows:
let searchConstraintsTrue = 'WHERE';
let firstItemTrue = 0;
for (const prop in req.body) {
if (req.body[prop] === 'TRUE') {
if (firstItemTrue === 0) {
searchConstraintsTrue += ` ${prop} = 1`;
firstItemTrue++;
} else {
searchConstraintsTrue += ` AND ${prop} = 1`;
}
}
}
let searchConstraintsMaybe = 'ORDER BY';
let firstItemMaybe = 0;
for (const prop in req.body) {
if (req.body[prop] === 'MAYBE') {
if (firstItemMaybe === 0) {
searchConstraintsMaybe += ` (${prop} = 1)::integer`;
firstItemMaybe++;
} else {
searchConstraintsMaybe += ` + (${prop} = 1)::integer`;
}
}
}
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
let sqlText = `SELECT * FROM venues
INNER JOIN response_enum rp ON rp.id = venues.parking
INNER JOIN response_enum rd ON rd.id = venues.decorations
INNER JOIN response_enum rh ON rh.id = venues.hotel
${searchConstraintsTrue} ${searchConstraintsMaybe} DESC`;
I realize that my searchConstraintsTrue and searchConstraintsMaybe are not properly using the enum table but right now I am just trying to get things working.
An example response looks like this:
[ {
id: 1,
name: 'beach',
parking: 1,
decorations: 2,
hotel: 1,
value: 'TRUE'
},
{
id: 2,
name: 'yard',
parking: 1,
decorations: 2,
hotel: 2,
value: 'FALSE'
}]
So I am returning the desired data however the id's are incorrect and there is a value column which doesn't exist in my database.
SELECT * will select all fields from the joined tables. You need to specify a list of fully qualified field names like so:
SELECT v.id,v.name,v.parking,v.decorations,v.hotel FROM venues v
INNER JOIN response_enum rp ON rp.id = venues.parking
INNER JOIN response_enum rd ON rd.id = venues.decorations
INNER JOIN response_enum rh ON rh.id = venues.hotel
${searchConstraintsTrue} ${searchConstraintsMaybe} DESC

AWS DynamoDB list distinct ID

I am developing something with nodejs and I have a table on DynamoDB. Therefore, I am using aws-sdk for nodejs to work with these two things.
Here is an example. ID and name are the combined key to the table.
ID name otherData
----------------------
1 Matt 123
1 Mary 1234
2 Mary 2312
4 Mary 3123
4 Pet 3123
What I want is to get a list of distinct ID. So, the expected output is
ID = [1, 2, 4]
How to do this?
1) Do a DynamoDB scan to get all (non-unique) ID values. The ProjectionExpression limits the result attributes returned, in this case to ID only. Note this doesn't make your scan any faster. When you execute the scan you will get a JSON object back containing your results. You can use JMES to get the ID array (data.Items.ID).
2) Make the array unique in your nodejs code (e.g. using the ArrNoDupe code function below)
var params = {
ProjectionExpression: "ID",
TableName: "YOUR_TABLE"
};
ddb.scan(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log(ArrNoDupe(data.Items.ID));
});
}
});
function ArrNoDupe(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}

Get field value from Array based on another field data matching

Below is my sample JSON object. I want to get the 'title' value based
on the longitude value. I have multiple(20-30) longitudes to get the titles, so I don't want to loop through those many times:
{
items:[
{
longitude:-72.897668,
latitude:40.453576,
title:52 street
},
{
longitude:-71.897668,
latitude:41.453576,
title:5th Ave
}
]
}
Can anyone suggest me how to get value without using for-loops.
Did you try something linke array.filter()?
function filterByLongitude(element) {
var expected = -72.897668
return element.longitude === expected;
}
var items = [{
longitude:-72.897668,
latitude:40.453576,
title:'52 street'
}, {
longitude:-71.897668,
latitude:41.453576,
title: '5th Ave'
}];
var match = items.filter(filterByLongitude);
console.log(match[0].title); // 52 street

Creating a Customer Refund record for a Customer Deposit associated with a Sales Order

I'm getting close. I'm am getting hung up on adding the Customer Deposit to the Customer Refund. Here is the code I am using to create a Customer Refund.
var ifxCreateCustomerRefund = {
fromSalesOrder: function () {
var salesOrder = nlapiGetNewRecord();
var customerRefund = nlapiCreateRecord('customerrefund');
customerRefund.setFieldValue("customer", salesOrder.getFieldValue("entity"));
customerRefund.setFieldValue("paymentmethod", salesOrder.getFieldValue("custbody_ifx_cc_payment_method"));
var account = ifxFindRecord.find("account", "number", "1099");
customerRefund.setFieldValue("account", account.id);
nlapiLogExecution("debug", "today", nlapiDateToString(nlapiStringToDate(this.today())));
customerRefund.setFieldValue("trandate", nlapiDateToString(nlapiStringToDate(this.today())));
nlapiLogExecution("debug", "order #", salesOrder.getFieldValue("tranid"));
nlapiLogExecution("debug", "deposittransaction", JSON.stringify(salesOrder.getFieldValue("deposittransaction")));
var deposits = nlapiSearchRecord("customerdeposit", null, new nlobjSearchFilter("createdfrom", null, "is", salesOrder.id), null);
nlapiLogExecution("debug", "customer deposits", JSON.stringify(deposits));
customerRefund.insertLineItem("deposit", 1);
customerRefund.setLineItemValue("deposit", "doc", 1, deposits[0].id);
customerRefund.setLineItemValue("deposit", "apply", 1, true);
nlapiSubmitRecord(customerRefund);
},
today: function () {
var dt = new Date();
var str = (dt.getMonth() + 1) + "/" + dt.getDay() + "/" + dt.getFullYear();
return nlapiDateToString(nlapiStringToDate(str));
}
};
It is giving me this error:
You have attempted an invalid sublist or line item operation. You are
either trying to access a field on a non-existent line or you are
trying to add or remove lines from a static sublist.
Can you help me get the Customer Deposit associated with the Sales Order to be applied to the Customer Refund?
The customer refund needs to be initialized with the customer id and then the available deposits will already be present. Adapted from my previous answer:
var cr = nlapiCreateRecord('customerrefund',{entity:salesOrder.getFieldValue("entity")}); // id of customer
cr.setFieldValue('paymentmethod', salesOrder.getFieldValue("custbody_ifx_cc_payment_method"));
... // do your account assignment etc.
var deposits = nlapiSearchRecord("customerdeposit", null, new nlobjSearchFilter("createdfrom", null, "is", salesOrder.getId()), null);
var depositId = deposits[0].getId();
for(var i = cr.getLineItemCount('deposit'); i>0; i--){
if(depositId == cr.getLineItemValue('deposit', 'doc', i)){
cr.setLineItemValue('deposit', 'apply', i, 'T'); // need this for at least one line.
break;
}
nlapiSubmitRecord(cr);

IndexedDB range limits

I'm using IndexedDb to store a person's city, email id and created_at.
I want to get all the people in a for a certain city with a valid email and sort by the created_at date.
I have a compound index query like so:
var city = "chennai";
var index_name = "city, " + "email, " + "created_at";
var index = store.index(index_name);
var boundedKeyRange = IDBKeyRange.bound([city, "", 0], [city, ??, ""]);
index.openCursor(boundedKeyRange, "prev").onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
// Check if email is valid and add it to an array
}
else {
// resolve a promise
}
}
The problem I have is that I don't know how to set the 'upper range' for email id's since # is a special character I'm not sure set the upper range to have all the email ids in the query.
Thank you
Deepak
The upper bound of a string can be taken as '\uFFFF' or [].
Anyways, your query will not work because you have two range query, "email" and "created_at". You can have only one key range query.

Resources