Scenario:
I have two MySQL databases:
- Big master database
- Small client database
Example tables:
Big Database User:
text username
- int id
- varchar login
- varchar password
- ... a lot more fields
Client Database User
- int id
- int UNIQUE api_id (id from master)
- varchar login
- varchar password
Problem: I need to synchronize databases, but i don't know how to do that in the best way. I read this question, but it's quite old, and not cover my case. I communicate with master database via REST API, direct connection is not the option.
My synchronization Algorithm
- Download and deserialize data from REST API ( for example /api/users/ ) to List of ApiUser objects
public class ApiUser {
int id;
string login;
string password;
}
public class User{
int id;
int api_id;
string login;
string password;
}
- Iterate over List of Apiusers
- If entity with ApiUser.id exist overwrite all fields
- Else create new entity
- Save changes
My code:
public void syncUsers(List <ApiUser> ApiUsers)
{
using (var db = new dbEntities())
{
ApiUsers.ForEach(apiUser =>
{
var dbUser = db.client
.Where(c => c.api_id == apiUser.id)
.SingleOrDefault();
if (dbUser == null)
{
var userObj = new user()
{
api_id = apiUser.id,
login = apiUser.login,
password = apiUser.password
};
db.client.Add(userObj);
}
else
{
dbUser.api_id = apiUser.id,
dbUser.login = apiUser.login,
dbUser.password = apiUser.password
}
});
db.SaveChanges();
}
}
Question: How to do it better? I have problem with deleted entities from master database, my algorithm does not cover cover this case.