How to update multiple rows of a database table in ASP.NET Core - entity-framework

I want to update multiple rows in ASP.NET Core, but I get an error:
InvalidOperationException: The entity type 'EntityQueryable' was not found. Ensure that the entity type has been added to the model.
This is my code:
var data = _db.UserTable.Where(a => a.CityIDn == selectedid);
foreach (var items in data)
{
await Task.Run(() =>
{
items.CityID = 2;
});
_db.Update(data);
await _db.SaveChangesAsync();
}

Try this for multiple rows:
var data = _db.UserTable.Where(a => a.CityIDn == selectedid).ToList();
foreach (var item in data)
{
item.CityID = 2;
_db.UserTable.Update(item);
}
await _db.SaveChangesAsync();
And for one record, try like this:
var data = _db.UserTable.Where(a => a.CityIDn == selectedid).FirstOrDefault();
if(data != null)
{
data.CityID = 2;
_db.UserTable.Update(data );
await _db.SaveChangesAsync();
}

The content of Update should be items, it worked for me, you can have a try.
var data = _db.UserTable.Where(a => a.CityIDn == selectedid).ToList();
foreach (var items in data)
{
await Task.Run(() =>
{
items.CityID = 2;
});
_db.Update(items);
await _db.SaveChangesAsync();
}

Related

how to update a collection if you already called it MongoDB Mongoos

Ok so I have a problem in which I use a collection to gather some ratings data and work with it, by the time I finish the rating update process, I have new ratings that I would like to update the collection with. However I can't call update because I get the error "Cannot overwrite model once compiled." I understand that I already called once the model to work with the data and that's why I get the error. is there any way I can update the collection? Or I will just have to workaround by creating a new collection with the latest rating, and then matching the latest ratings collection with the one I use to work with the data.
This is my code
let calculateRating = async () => {
const getData = await matchesCollection().find().lean();
const playerCollection = await playersCollection();
const getDataPlayer = await playerCollection.find().lean();
let gamesCounting = [];
getDataPlayer.forEach((player) => {
player.makePlayer = ranking.makePlayer(1500);
});
for (let i = 0; i < getData.length; i++) {
const resultA = getDataPlayer.findIndex(({ userId }, index) => {
if (userId === getData[i].userA) {
return index;
}
});
const resultB = getDataPlayer.findIndex(
({ userId }) => userId === getData[i].userB
);
const winner = getData[i].winner;
if (getDataPlayer[resultA] === undefined) {
continue;
} else if (getDataPlayer[resultB] === undefined) {
continue;
}
gamesCounting.push([
getDataPlayer[resultA].makePlayer,
getDataPlayer[resultB].makePlayer,
winner,
]);
}
ranking.updateRatings(gamesCounting);
let ratingsUpdate = [];
getDataPlayer.forEach((item) => {
let newRating = item.makePlayer.getRating();
let newDeviation = item.makePlayer.getRd();
let newVolatility = item.makePlayer.getVol();
item.rating = newRating;
item.rd = newDeviation;
item.vol = newVolatility;
ratingsUpdate.push(item);
});
};
I try the work around with creating the new collection

Excel flutter read data by columns

Is it possible to fetch the data existing in a file.xlsx using Excel dependency by columns?
I mean for each column that exist in the sheet it should be stored in a list for example.
I have only found how to fetch data by rows using:
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// code
}
}
Is there any way to do this by columns?
Thank you.
I think this code from example is you need:
/// Iterating and changing values to desired type
for (int row = 0; row < sheet.maxRows; row++) {
sheet.row(row).forEach((cell) {
var val = cell.value; // Value stored in the particular cell
});
}
Found a temporary solution, downside is that you need to get column heading(s) for getting their values, below is the code if it helps you out:
Future<List<ExcelSheetData>> getExcelFile(BuildContext context, String name, String email) async {
FilePickerResult pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['xlsx'],
allowMultiple: false,
);
List<ExcelSheetData> excelList = [];
int nameIndex;
int emailIndex;
if (pickedFile != null) {
setAddMembersLoadingTrue();
var file = pickedFile.paths.single;
var bytes = await File(file).readAsBytes();
Excel excel = await compute(parseExcelFile, bytes);
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// name variable is for Name of Column Heading for Name
if (row?.any((element) => element?.value?.toString() == name) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == name);
nameIndex = data.colIndex;
}
// email variable is for Name of Column Heading for Email
if (row?.any((element) => element?.value?.toString() == email) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == email);
emailIndex = data.colIndex;
}
if (nameIndex != null && emailIndex != null) {
if (row[nameIndex]?.value.toString().toLowerCase() != name.toLowerCase() && row[emailIndex]?.value.toString().toLowerCase() != email.toLowerCase())
excelList.add(
ExcelSheetData(
name: row[nameIndex]?.value.toString(),
email: row[emailIndex]?.value.toString(),
),
);
}
}
}
setAddMembersLoadingFalse();
return excelList;
}
return null;
}
refer to this question if you need more clarification

Remove and Insert in table , Removing previous data using Entity frame work in asp.net core

When trying to insert "FromCompany" data to "ToCompany" after saveChanges(); it deleted "FromCompany" data.
I am trying to delete old data , and copy the data from another company to mycompany, but it deleting the data from that comapny after saving it in my company.
This is the example code:
foreach (var data in ctx.AllData.Where(a => a.CompanyId == toCompanyId).Select(a => a).ToList())
{
ctx.AllData.Remove(data);
}
ctx.SaveChanges();
var alldata = ctx.AllData.Where(a => a.CompanyId == fromCompanyId ).Select(a => a).ToList();
foreach (var data in alldata)
{
var model = new AllData();
data.CompanyId = toCompanyId;
model.CompanyId = data.CompanyId;
model.CategoryId = data.CategoryId;
model.OtherFields = data.OtherFields;
ctx.AllData.Add(model);
}
ctx.SaveChanges();
In the second foreach you are changing the data.CompanyId. Then calling ctx.SaveChanges you are changing all companies with fromCompanyId. Try to remove that line, like this:
foreach (var data in ctx.AllData.Where(a => a.CompanyId == toCompanyId).Select(a => a).ToList())
{
ctx.AllData.Remove(data);
}
ctx.SaveChanges();
var alldata = ctx.AllData.Where(a => a.CompanyId == fromCompanyId ).Select(a => a).ToList();
foreach (var data in alldata)
{
var model = new AllData();
model.CompanyId = toCompanyId;
model.CategoryId = data.CategoryId;
model.OtherFields = data.OtherFields;
ctx.AllData.Add(model);
}
ctx.SaveChanges();
While you are calling ctx.SaveChanges you are saving all changes were performed in all context's data.

clean future builder for new data

i'm using a builder for a search page in my application, basically i get data from a json file,
my issue is that if i try to search for a new word, the old result will still be shown and the new one are going to be shown under them.
here is how i get data from my website:
Future<List<Note>> fetchNotes() async {
var url = 'https://sample.com/';
var response = await http.get(url + _controller.text.trim());
var notes = List<Note>();
if (response.statusCode == 200) {
var notesJson = json.decode(response.body);
for (var noteJson in notesJson) {
notes.add(Note.fromJson(noteJson));
}
} else {
ercode = 1;
}
return notes;
}
fetchNotes().then((value) {
setState(() {
_notes.addAll(value);
});
});
if (_notes[0] == null) {
ercode = 2;
}
}
and i display data like this:
here is full example for showing that data
I think you should use "clear()".
fetchNotes().then((value) {
setState(() {
_notes.clear();
_notes.addAll(value);
});
});

Transaction not working with Web API .net core 2.2

I have a async web API that has services and a connection to the db using an EF context.
In one of the services, where I inject the context using DI I want to make a simple transactional service, like:
public async Task<int> ServiceMethod()
{
using (var transaction = context.Database.BeginTransaction())
{
await context.Table1.AddAsync(new Table1());
await context.SaveChangeAsync();
CallOtherservice(context);
await context.SaveChangeAsync();
transaction.Commit();
}
}
CallOtherService(Context context)
{
await context.Table2.AddAsync();
}
I have now mocked CallOtherService() to throw an exception and I expect nothing to be commited, but it looks like changes to Table1 persist, amid the transaction trhat should stop them. I have tried calling Rollback() in a try catch statement and using a TransactionScope() instead, but both were useless. Also, I have noticed that after calling .BeginTransaction(), context.Database.CurrentTransaction is null, which I consider a bit weird.
EDIT:
the method that I test:
public async Task<int> AddMatchAsync(Models.Database.Match match)
{
//If match is null, nothing can be done
if (match == null)
return 0;
else
{
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
//If the match already exists, return its id
var dbId = await ExistsMatchAsync(match.HomeTeam.Name, match.AwayTeam.Name, match.Time);
if (dbId > 0)
{
log.Info($"Found match with id {dbId}");
return dbId;
}
//add computable data
match = await AttachMatchName(match);
match.Season = CommonServices.toSeason(match);
// Prepare the relational entities accordingly
match = PrepareTeamsForAddMatch(match).Result;
match = PrepareLeagueForAddMatch(match).Result;
//add the match and save it to the DB
await context.Matches.AddAsync(match);
await context.SaveChangesAsync();
log.Info($"Successfully added a new match! id: {match.Id}");
// Create new TeamLeagues entities if needed
leaguesService.CreateTeamLeaguesForNewMatchAsync(context, match);
await context.SaveChangesAsync();
scope.Complete();
return match.Id;
}
catch (Exception ex)
{
log.Error($"Error adding match - Rolling back: {ex}");
throw;
}
}
}
}
and the test:
[Test]
public void AddMatchSaveChangesTransaction()
{
//Arrange
var exceptiontext = "This exception should prevent the match from being saved";
var leagueServiceMock = new Mock<ILeaguesService>();
leagueServiceMock.Setup(p => p.CreateTeamLeaguesForNewMatchAsync(It.IsAny<InFormCoreContext>(),It.IsAny<Match>()))
.Throws(new Exception(exceptiontext));
leagueServiceMock.Setup(p => p.GetLeagueAsync(It.IsAny<string>()))
.ReturnsAsync((string name) => new League{Id = 1, Name = name });
var match = new Match
{
HomeTeam = new Team { Name = "Liverpool" },
AwayTeam = new Team { Name = "Everton" },
League = new League { Name = "PL", IsSummer = true },
Time = DateTime.UtcNow,
HomeGoals = 3,
AwayGoals = 0
};
var mcount = context.Matches.Count();
//Act
var matchService = new MatchesService(context, leagueServiceMock.Object, new LogNLog(), TeamsService);
//Assert
var ex = Assert.ThrowsAsync<Exception>(async () => await matchService.AddMatchAsync(match));
Assert.AreEqual(ex.Message, exceptiontext);
Assert.AreEqual(mcount, context.Matches.Count(), "The match has been added - the transaction does not work");
}`
```