开发者

After calling a stored procedure by Entity Framework, tables update in database, but entities remain as they were

开发者 https://www.devze.com 2023-02-17 10:23 出处:网络
I created two stored procedures in SQL Server Management Studio. First procedure add field in ProjcetsToUsers table (for many-to-many associations)

I created two stored procedures in SQL Server Management Studio.

First procedure add field in ProjcetsToUsers table (for many-to-many associations)

CREATE PROCEDURE sp_addUserToProject
    @userId int,
    @projectId int
AS
BEGIN
    SET NOCOUNT ON;             
    IF NOT EXISTS(SELECT * FROM ProjectsToUsers WHERE idProject = @projectId and idUser = @userId)  
        INSERT INTO ProjectsToUsers (idProject, idUser) VALUES (@projectId, @userId)    
END
GO

Second procedure delete field from this table:

CREATE PROCEDURE sp_deleteUserToProject
    @userId int,
    @projectId int
AS
BEGIN
    SET NOCOUNT ON;         
    DELETE FROM ProjectsToUsers WHERE idProject = @projectId and idUser = @userId       
END
GO

First function import update all date (in data base and entities in session):

Entities.AddUserToProject(projectId: project.id, userId: user.id);

Second function import update only field in data base =(

bugTrackerEntities.DeleteUserFromProject(projectId: project.id, userId: user.id);

I tried refresh entites:

bugTrackerEntities.Refresh(RefreshMode.StoreWins, project);
bugTrackerEntities.Refresh(RefreshMode.StoreWins, user);
bugTrackerEntities.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
project.Users.L开发者_StackOverflow中文版oad();
user.Projects.Load();

it didn't help =(

I can delete the user from the project and then add another, and the new one is added but removed the remains. As for data base both this function work correctly.

Why this happens?


If you have both user and project entities in your application you don't need these procedures at all. Simply use:

project.Users.Add(user);

And

project.Users.Remove(user);

The reason why this happens is that EF doesn't know that relation has changed. Try this to refresh relations:

bugTrackerEntities.LoadProperty<Project>(project, p => p.Users,  
    MergeOptions.OverwriteChanges); 

I'm affraid that it will still have a problem with deleted relation - at least in version EFv1 (.NET 3.5 SP1) it wasn't able to remove existing relation which wasn't loaded from database.

0

精彩评论

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