简体   繁体   中英

C# Insert missing records, from a list with linq?

I have an incomplete table of user settings. Now i have a small program that pulls settings from this table. How can i ensure that there is a record for that user in the database?

I got this list

List<Guid> usersWithoutInfo

This list contains the user ids that i need to pull the settings for. How can i first loop through this list and insert the missing records? I am using a linq data context for all data handling.

Should be something like this. You'll have to tweak it a bit to compile and work for you

List<Guid> usersWithoutInfo = new List<Guid>(){......};

var usersToInsert = usersWithoutInfo.Where(userGuid => !usertableInDB.Contains(userGuid)).ToList();

Then use the usersToInsert to insert users in the database

I'd use the equivalent of SQL LEFT JOIN statement. Below statement will produce the list of users to check against existing ones paired with the existing user name. Those elements that have paired name as NULL need to be inserted:

        List<string> users = new List<string> { "User1", "User3", "User5"};
        List<string> usersToCheck = new List<string> { "User1", "User2", "User4", "User5" };

        var leftJoin = 
            from userToCheck in usersToCheck
            join existingUser in users
                on userToCheck equals existingUser into joined
            from existingUser in joined.DefaultIfEmpty()
            select new
            {
                userToInsert = userToCheck,
                user = existingUser ?? null
            };

You may add WHERE before SELECT to filter out matching entries.

Use a simple foreach loop to iterate through your list, then use the Any keyword to see if any records for that Guid exist.

var newSettings = new List<SettingsTableRecord>();
foreach (var userGuid in usersWithoutInfo) {
    if(!context.SettingsTableRecords.Any(u=>u.UserGuid.Equals(userGuid)){
        //do work to crate records, such as
        newSettings.Add(new SettingsTableRecord {UserGuid = userGuid, Email="Hi!"});
    }
}
//insert the new records
context.SettingsTableRecords.InsertAllOnSubmit(newSettings);
context.SubmitChanges();

Substitute your table name for "SettingsTable" and your Guid field for "UserGuid", obviously.

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