Synchronize DbContext with changes in Database












2














I am currently developing a multi user data management system in .NET 4.0.



My frontend is a WPF application which retrieves all the data from a SqlExpress Server. I am using the latest Entityframework version as main datalayer to read and write to the database.



The software has to handle following scenario. Each Frontend (WPF Application) can add and modify data in the database which is created by the client hisself. The client is not allowed to modify / delete records from other users therefore each Entity has stored the username information on the main entity.



Here you can see the datamodel I am using (EF Code First Approach).



enter image description here



I am using this Query to load all the data into the frontend application:



public static Context GetDataContext()
{
return new Context(Settings.ServerConnection);
}

public Project LoadProject(int id)
{
Remoting.Context = GetDataContext();
Project = Remoting.Context.dbsProjects.Where(p => p.Id == id)
.Include(p => p.Categories.Select(x => x.Templates.Select(y=>y.Properties.Select(xx=>xx.Binding))))
.Include(p => p.Categories.Select(x => x.Templates.Select(y => y.Links)))
.Include(p => p.DataSources).FirstOrDefault();

OnPropertyChanged("Project");
return Project;
}


After that initial load all data is displayed correctly in my frontend. So far so good that was the easy part.



Now I want to synchronize my DbContext, which is a long living context, lives for the complete runtime of the MainWindow. Means when another frontend inserts updates data which belongs to him, I want to display it also in all the other clients.



I have found a solution how to refresh all already existing entities within one context, therefore I use this lines of code:



var refreshableObjects = Remoting.Context.ChangeTracker.Entries().Select(c => c.Entity).ToList();
Remoting.Context.ObjectContext.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, refreshableObjects);


I am not sure if this is the right solution, but so far it works for me.



So far i can refresh all already loaded entities, but i have no idea how i can detect entities which are created or deleted by another frontend which is running at the same time. Is there any build in mechanism to refresh the initial linq query that loads or removes entities which are new in the database?



Thanks for your help!










share|improve this question






















  • I'd try Remoting.Context.Entry(Project).Reload(); and see if it gets child objects too.
    – C.M.
    Nov 26 '18 at 16:00










  • @C.M.unfortiunatly this does not work, it only refreshes all existing entities but does not load new ones or remove old ones.
    – Manuel Bleimuth
    Nov 26 '18 at 16:39










  • Why do you need long living context? In general i would try to create contextPerRequest, if it's impossible, you can turn off change tracker by Configuration.AutoDetectChangesEnabled = false; or AsNoTracking.
    – zxxc
    Dec 3 '18 at 9:45










  • @zxxc, i think i need a long living context as the data is displayed in multiple windows (avalondock) and the user also has the possibility to manipulate this data. How should i track changes if i do not have a long living context?
    – Manuel Bleimuth
    Dec 3 '18 at 11:37










  • Why don't use a service WCF to provide data and changes ?
    – Shim-Sao
    Dec 3 '18 at 12:10


















2














I am currently developing a multi user data management system in .NET 4.0.



My frontend is a WPF application which retrieves all the data from a SqlExpress Server. I am using the latest Entityframework version as main datalayer to read and write to the database.



The software has to handle following scenario. Each Frontend (WPF Application) can add and modify data in the database which is created by the client hisself. The client is not allowed to modify / delete records from other users therefore each Entity has stored the username information on the main entity.



Here you can see the datamodel I am using (EF Code First Approach).



enter image description here



I am using this Query to load all the data into the frontend application:



public static Context GetDataContext()
{
return new Context(Settings.ServerConnection);
}

public Project LoadProject(int id)
{
Remoting.Context = GetDataContext();
Project = Remoting.Context.dbsProjects.Where(p => p.Id == id)
.Include(p => p.Categories.Select(x => x.Templates.Select(y=>y.Properties.Select(xx=>xx.Binding))))
.Include(p => p.Categories.Select(x => x.Templates.Select(y => y.Links)))
.Include(p => p.DataSources).FirstOrDefault();

OnPropertyChanged("Project");
return Project;
}


After that initial load all data is displayed correctly in my frontend. So far so good that was the easy part.



Now I want to synchronize my DbContext, which is a long living context, lives for the complete runtime of the MainWindow. Means when another frontend inserts updates data which belongs to him, I want to display it also in all the other clients.



I have found a solution how to refresh all already existing entities within one context, therefore I use this lines of code:



var refreshableObjects = Remoting.Context.ChangeTracker.Entries().Select(c => c.Entity).ToList();
Remoting.Context.ObjectContext.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, refreshableObjects);


I am not sure if this is the right solution, but so far it works for me.



So far i can refresh all already loaded entities, but i have no idea how i can detect entities which are created or deleted by another frontend which is running at the same time. Is there any build in mechanism to refresh the initial linq query that loads or removes entities which are new in the database?



Thanks for your help!










share|improve this question






















  • I'd try Remoting.Context.Entry(Project).Reload(); and see if it gets child objects too.
    – C.M.
    Nov 26 '18 at 16:00










  • @C.M.unfortiunatly this does not work, it only refreshes all existing entities but does not load new ones or remove old ones.
    – Manuel Bleimuth
    Nov 26 '18 at 16:39










  • Why do you need long living context? In general i would try to create contextPerRequest, if it's impossible, you can turn off change tracker by Configuration.AutoDetectChangesEnabled = false; or AsNoTracking.
    – zxxc
    Dec 3 '18 at 9:45










  • @zxxc, i think i need a long living context as the data is displayed in multiple windows (avalondock) and the user also has the possibility to manipulate this data. How should i track changes if i do not have a long living context?
    – Manuel Bleimuth
    Dec 3 '18 at 11:37










  • Why don't use a service WCF to provide data and changes ?
    – Shim-Sao
    Dec 3 '18 at 12:10
















2












2








2







I am currently developing a multi user data management system in .NET 4.0.



My frontend is a WPF application which retrieves all the data from a SqlExpress Server. I am using the latest Entityframework version as main datalayer to read and write to the database.



The software has to handle following scenario. Each Frontend (WPF Application) can add and modify data in the database which is created by the client hisself. The client is not allowed to modify / delete records from other users therefore each Entity has stored the username information on the main entity.



Here you can see the datamodel I am using (EF Code First Approach).



enter image description here



I am using this Query to load all the data into the frontend application:



public static Context GetDataContext()
{
return new Context(Settings.ServerConnection);
}

public Project LoadProject(int id)
{
Remoting.Context = GetDataContext();
Project = Remoting.Context.dbsProjects.Where(p => p.Id == id)
.Include(p => p.Categories.Select(x => x.Templates.Select(y=>y.Properties.Select(xx=>xx.Binding))))
.Include(p => p.Categories.Select(x => x.Templates.Select(y => y.Links)))
.Include(p => p.DataSources).FirstOrDefault();

OnPropertyChanged("Project");
return Project;
}


After that initial load all data is displayed correctly in my frontend. So far so good that was the easy part.



Now I want to synchronize my DbContext, which is a long living context, lives for the complete runtime of the MainWindow. Means when another frontend inserts updates data which belongs to him, I want to display it also in all the other clients.



I have found a solution how to refresh all already existing entities within one context, therefore I use this lines of code:



var refreshableObjects = Remoting.Context.ChangeTracker.Entries().Select(c => c.Entity).ToList();
Remoting.Context.ObjectContext.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, refreshableObjects);


I am not sure if this is the right solution, but so far it works for me.



So far i can refresh all already loaded entities, but i have no idea how i can detect entities which are created or deleted by another frontend which is running at the same time. Is there any build in mechanism to refresh the initial linq query that loads or removes entities which are new in the database?



Thanks for your help!










share|improve this question













I am currently developing a multi user data management system in .NET 4.0.



My frontend is a WPF application which retrieves all the data from a SqlExpress Server. I am using the latest Entityframework version as main datalayer to read and write to the database.



The software has to handle following scenario. Each Frontend (WPF Application) can add and modify data in the database which is created by the client hisself. The client is not allowed to modify / delete records from other users therefore each Entity has stored the username information on the main entity.



Here you can see the datamodel I am using (EF Code First Approach).



enter image description here



I am using this Query to load all the data into the frontend application:



public static Context GetDataContext()
{
return new Context(Settings.ServerConnection);
}

public Project LoadProject(int id)
{
Remoting.Context = GetDataContext();
Project = Remoting.Context.dbsProjects.Where(p => p.Id == id)
.Include(p => p.Categories.Select(x => x.Templates.Select(y=>y.Properties.Select(xx=>xx.Binding))))
.Include(p => p.Categories.Select(x => x.Templates.Select(y => y.Links)))
.Include(p => p.DataSources).FirstOrDefault();

OnPropertyChanged("Project");
return Project;
}


After that initial load all data is displayed correctly in my frontend. So far so good that was the easy part.



Now I want to synchronize my DbContext, which is a long living context, lives for the complete runtime of the MainWindow. Means when another frontend inserts updates data which belongs to him, I want to display it also in all the other clients.



I have found a solution how to refresh all already existing entities within one context, therefore I use this lines of code:



var refreshableObjects = Remoting.Context.ChangeTracker.Entries().Select(c => c.Entity).ToList();
Remoting.Context.ObjectContext.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, refreshableObjects);


I am not sure if this is the right solution, but so far it works for me.



So far i can refresh all already loaded entities, but i have no idea how i can detect entities which are created or deleted by another frontend which is running at the same time. Is there any build in mechanism to refresh the initial linq query that loads or removes entities which are new in the database?



Thanks for your help!







c# entity-framework






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 12:13









Manuel Bleimuth

40112




40112












  • I'd try Remoting.Context.Entry(Project).Reload(); and see if it gets child objects too.
    – C.M.
    Nov 26 '18 at 16:00










  • @C.M.unfortiunatly this does not work, it only refreshes all existing entities but does not load new ones or remove old ones.
    – Manuel Bleimuth
    Nov 26 '18 at 16:39










  • Why do you need long living context? In general i would try to create contextPerRequest, if it's impossible, you can turn off change tracker by Configuration.AutoDetectChangesEnabled = false; or AsNoTracking.
    – zxxc
    Dec 3 '18 at 9:45










  • @zxxc, i think i need a long living context as the data is displayed in multiple windows (avalondock) and the user also has the possibility to manipulate this data. How should i track changes if i do not have a long living context?
    – Manuel Bleimuth
    Dec 3 '18 at 11:37










  • Why don't use a service WCF to provide data and changes ?
    – Shim-Sao
    Dec 3 '18 at 12:10




















  • I'd try Remoting.Context.Entry(Project).Reload(); and see if it gets child objects too.
    – C.M.
    Nov 26 '18 at 16:00










  • @C.M.unfortiunatly this does not work, it only refreshes all existing entities but does not load new ones or remove old ones.
    – Manuel Bleimuth
    Nov 26 '18 at 16:39










  • Why do you need long living context? In general i would try to create contextPerRequest, if it's impossible, you can turn off change tracker by Configuration.AutoDetectChangesEnabled = false; or AsNoTracking.
    – zxxc
    Dec 3 '18 at 9:45










  • @zxxc, i think i need a long living context as the data is displayed in multiple windows (avalondock) and the user also has the possibility to manipulate this data. How should i track changes if i do not have a long living context?
    – Manuel Bleimuth
    Dec 3 '18 at 11:37










  • Why don't use a service WCF to provide data and changes ?
    – Shim-Sao
    Dec 3 '18 at 12:10


















I'd try Remoting.Context.Entry(Project).Reload(); and see if it gets child objects too.
– C.M.
Nov 26 '18 at 16:00




I'd try Remoting.Context.Entry(Project).Reload(); and see if it gets child objects too.
– C.M.
Nov 26 '18 at 16:00












@C.M.unfortiunatly this does not work, it only refreshes all existing entities but does not load new ones or remove old ones.
– Manuel Bleimuth
Nov 26 '18 at 16:39




@C.M.unfortiunatly this does not work, it only refreshes all existing entities but does not load new ones or remove old ones.
– Manuel Bleimuth
Nov 26 '18 at 16:39












Why do you need long living context? In general i would try to create contextPerRequest, if it's impossible, you can turn off change tracker by Configuration.AutoDetectChangesEnabled = false; or AsNoTracking.
– zxxc
Dec 3 '18 at 9:45




Why do you need long living context? In general i would try to create contextPerRequest, if it's impossible, you can turn off change tracker by Configuration.AutoDetectChangesEnabled = false; or AsNoTracking.
– zxxc
Dec 3 '18 at 9:45












@zxxc, i think i need a long living context as the data is displayed in multiple windows (avalondock) and the user also has the possibility to manipulate this data. How should i track changes if i do not have a long living context?
– Manuel Bleimuth
Dec 3 '18 at 11:37




@zxxc, i think i need a long living context as the data is displayed in multiple windows (avalondock) and the user also has the possibility to manipulate this data. How should i track changes if i do not have a long living context?
– Manuel Bleimuth
Dec 3 '18 at 11:37












Why don't use a service WCF to provide data and changes ?
– Shim-Sao
Dec 3 '18 at 12:10






Why don't use a service WCF to provide data and changes ?
– Shim-Sao
Dec 3 '18 at 12:10














1 Answer
1






active

oldest

votes


















2





+25









I solved this issue years ago by using Service Broker. I have done a little research about this issue about how this is solved nowadays and it seems that it is done the same way. Searching on GitHub I found the following project that should suit your needs:
monitor-table-change-with-sqltabledependency



Using this library you can listen on the SqlTableDependency.Change-event and get notified when entries on a table are updated, inserted, deleted.strong text






share|improve this answer





















  • This one looks really promising. I have 2 questions regarding this solution. Right now the Change Event triggers every time when something is inserted/deleted/updated, is there any possiblity to find out which client the update did, means when one client makes a change the client itself also gets the notification but this one does not need to update as he was the updating client. The second thing is i could not make it work using sql windows authentication, is there any limitation on this?
    – Manuel Bleimuth
    Nov 27 '18 at 16:31












  • @ManuelBleimuth for Question 1: just query the data and throw the result away if the data is from the current client. There should not be any performance issue if you query X or X-1 times. Question 2: does it work with any other authentication method? please be ware of the permissions you need. Please see the readme on the GitHub repository.
    – Michael Mairegger
    Nov 28 '18 at 13:51











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53411803%2fsynchronize-dbcontext-with-changes-in-database%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2





+25









I solved this issue years ago by using Service Broker. I have done a little research about this issue about how this is solved nowadays and it seems that it is done the same way. Searching on GitHub I found the following project that should suit your needs:
monitor-table-change-with-sqltabledependency



Using this library you can listen on the SqlTableDependency.Change-event and get notified when entries on a table are updated, inserted, deleted.strong text






share|improve this answer





















  • This one looks really promising. I have 2 questions regarding this solution. Right now the Change Event triggers every time when something is inserted/deleted/updated, is there any possiblity to find out which client the update did, means when one client makes a change the client itself also gets the notification but this one does not need to update as he was the updating client. The second thing is i could not make it work using sql windows authentication, is there any limitation on this?
    – Manuel Bleimuth
    Nov 27 '18 at 16:31












  • @ManuelBleimuth for Question 1: just query the data and throw the result away if the data is from the current client. There should not be any performance issue if you query X or X-1 times. Question 2: does it work with any other authentication method? please be ware of the permissions you need. Please see the readme on the GitHub repository.
    – Michael Mairegger
    Nov 28 '18 at 13:51
















2





+25









I solved this issue years ago by using Service Broker. I have done a little research about this issue about how this is solved nowadays and it seems that it is done the same way. Searching on GitHub I found the following project that should suit your needs:
monitor-table-change-with-sqltabledependency



Using this library you can listen on the SqlTableDependency.Change-event and get notified when entries on a table are updated, inserted, deleted.strong text






share|improve this answer





















  • This one looks really promising. I have 2 questions regarding this solution. Right now the Change Event triggers every time when something is inserted/deleted/updated, is there any possiblity to find out which client the update did, means when one client makes a change the client itself also gets the notification but this one does not need to update as he was the updating client. The second thing is i could not make it work using sql windows authentication, is there any limitation on this?
    – Manuel Bleimuth
    Nov 27 '18 at 16:31












  • @ManuelBleimuth for Question 1: just query the data and throw the result away if the data is from the current client. There should not be any performance issue if you query X or X-1 times. Question 2: does it work with any other authentication method? please be ware of the permissions you need. Please see the readme on the GitHub repository.
    – Michael Mairegger
    Nov 28 '18 at 13:51














2





+25







2





+25



2




+25




I solved this issue years ago by using Service Broker. I have done a little research about this issue about how this is solved nowadays and it seems that it is done the same way. Searching on GitHub I found the following project that should suit your needs:
monitor-table-change-with-sqltabledependency



Using this library you can listen on the SqlTableDependency.Change-event and get notified when entries on a table are updated, inserted, deleted.strong text






share|improve this answer












I solved this issue years ago by using Service Broker. I have done a little research about this issue about how this is solved nowadays and it seems that it is done the same way. Searching on GitHub I found the following project that should suit your needs:
monitor-table-change-with-sqltabledependency



Using this library you can listen on the SqlTableDependency.Change-event and get notified when entries on a table are updated, inserted, deleted.strong text







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 27 '18 at 6:34









Michael Mairegger

5,3432234




5,3432234












  • This one looks really promising. I have 2 questions regarding this solution. Right now the Change Event triggers every time when something is inserted/deleted/updated, is there any possiblity to find out which client the update did, means when one client makes a change the client itself also gets the notification but this one does not need to update as he was the updating client. The second thing is i could not make it work using sql windows authentication, is there any limitation on this?
    – Manuel Bleimuth
    Nov 27 '18 at 16:31












  • @ManuelBleimuth for Question 1: just query the data and throw the result away if the data is from the current client. There should not be any performance issue if you query X or X-1 times. Question 2: does it work with any other authentication method? please be ware of the permissions you need. Please see the readme on the GitHub repository.
    – Michael Mairegger
    Nov 28 '18 at 13:51


















  • This one looks really promising. I have 2 questions regarding this solution. Right now the Change Event triggers every time when something is inserted/deleted/updated, is there any possiblity to find out which client the update did, means when one client makes a change the client itself also gets the notification but this one does not need to update as he was the updating client. The second thing is i could not make it work using sql windows authentication, is there any limitation on this?
    – Manuel Bleimuth
    Nov 27 '18 at 16:31












  • @ManuelBleimuth for Question 1: just query the data and throw the result away if the data is from the current client. There should not be any performance issue if you query X or X-1 times. Question 2: does it work with any other authentication method? please be ware of the permissions you need. Please see the readme on the GitHub repository.
    – Michael Mairegger
    Nov 28 '18 at 13:51
















This one looks really promising. I have 2 questions regarding this solution. Right now the Change Event triggers every time when something is inserted/deleted/updated, is there any possiblity to find out which client the update did, means when one client makes a change the client itself also gets the notification but this one does not need to update as he was the updating client. The second thing is i could not make it work using sql windows authentication, is there any limitation on this?
– Manuel Bleimuth
Nov 27 '18 at 16:31






This one looks really promising. I have 2 questions regarding this solution. Right now the Change Event triggers every time when something is inserted/deleted/updated, is there any possiblity to find out which client the update did, means when one client makes a change the client itself also gets the notification but this one does not need to update as he was the updating client. The second thing is i could not make it work using sql windows authentication, is there any limitation on this?
– Manuel Bleimuth
Nov 27 '18 at 16:31














@ManuelBleimuth for Question 1: just query the data and throw the result away if the data is from the current client. There should not be any performance issue if you query X or X-1 times. Question 2: does it work with any other authentication method? please be ware of the permissions you need. Please see the readme on the GitHub repository.
– Michael Mairegger
Nov 28 '18 at 13:51




@ManuelBleimuth for Question 1: just query the data and throw the result away if the data is from the current client. There should not be any performance issue if you query X or X-1 times. Question 2: does it work with any other authentication method? please be ware of the permissions you need. Please see the readme on the GitHub repository.
– Michael Mairegger
Nov 28 '18 at 13:51


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53411803%2fsynchronize-dbcontext-with-changes-in-database%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

Refactoring coordinates for Minecraft Pi buildings written in Python