简体   繁体   中英

.net core api database context foreach

Momentarily i am working on an API. I just deployed my API to an online environment. now my problem i came across is the following:

Locally, my API had no problems whatsoever, the problem started when i deployed it.

I debugged my program and this was the problem:

var setups = _context.Setup;

 foreach (var setup in setups) //<-- problem
                {
                    if (setup.SetupID == setupItems.SetupID)
                    {
                        setup.SetupName = setupItems.SetupName;
                        counter++; //if it is already  in the database
                    }
                }

My new MSSQL database gets stuck on this foreach loop, it returns a 404 error the moment it gets in. For comparison underneath are the developer as well as the deployment connection string:

Development

Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=***;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False; MultipleActiveResultSets=true

Deployment

Data Source=***;Initial Catalog=***;User ID=***;Password=***;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true

Question How do I solve this issue?

UPDATE

The problem is that my online database items are not recognized. I tried validating my connection string using this method in console:

$conn.ConnectionString = "myConncetionString" # whatever you are testing
$conn.Open()
$conn.Close()

The connection string connected perfectly.

I migrated all the tables in it as well that won't be the problem. for info I am using MSSQL MyLittleAdmin as database. Permissions are not the problem either.

Do you receiving any exception in your code? Please share exact exception you are receiving in your code.

You have two issues here - first: you should materialize the query (_context.Setup.ToList()) otherwise each row is materializing separately what generates a lot of communication between your app and the db. Secund: if your query (collection) will be materialized it is good idea to to stop tracking the changes in the foreach - better is to "search for the changes" just before "Save Changes" to the db

Here is the code, as I would implement it:

var setups = _context.Setup.Where(x => x.SetupID == setupItems.SetupID).ToList();

foreach (var setup in setups)
{
   setup.SetupName = setupItems.SetupName;
}

I think I don't know exact context of your code - foreach through all records in the table is not very good idea:) even your exact issue is somewhere else..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM