开发者

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

开发者 https://www.devze.com 2023-02-06 09:24 出处:网络
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 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.开发者_Go百科


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消