Aftab Ahmed
Aftab Ahmed

Reputation: 905

How to check whether model have some changes in C# MVC

I have appSourceInfoModel taken from Database, now i am passing ViewModel i.e. reviewerAppsBacklogViewModel and if reviewerAppsBacklogViewModel and appSourceInfoModel are same then do not update database if there are changes then Update. I am doing, first assigning to variable var DBappSourceInfoModel = appSourceInfoModel; then I assigning some values to appSourceInfoModel then comparing the initially saved model DBappSourceInfoModel and appSourceInfoModel. But, assigning some values to appSourceInfoModel also change values in the initially saved model DBappSourceInfoModel. All of the code can be found below.

AppSourceInfo appSourceInfoModel = _appSourceInfoRepository.Get(a => a.Review.ReviewId == reviewId);

var DBappSourceInfoModel = appSourceInfoModel; //Initially save Model in var

appSourceInfoModel.Cost = reviewerAppsBacklogViewModel.Cost;
appSourceInfoModel.InProgress = true;
appSourceInfoModel.PegiRating = reviewerAppsBacklogViewModel.PegiRating;
appSourceInfoModel.Rating = reviewerAppsBacklogViewModel.AverageUserReviewsRating;
appSourceInfoModel.DownloadCounter = reviewerAppsBacklogViewModel.NoofDownloadsFromSource;
appSourceInfoModel.ReviewCounter = reviewerAppsBacklogViewModel.NoofReviewOfSource;
appSourceInfoModel.StoreCategory = reviewerAppsBacklogViewModel.StoreCategory;

var IsAppSourceInfoModelChanged = !DBappSourceInfoModel.Equals(appSourceInfoModel);
if (IsAppSourceInfoModelChanged)
{
    _appSourceInfoRepository.Update(appSourceInfoModel);
}

I have Solved it using this simple Code in My Model i.e. AppSourceInfo

 public object Clone()
    {
        return this.MemberwiseClone();
    }

and change the following code

var DBappSourceInfoModel = appSourceInfoModel; //Initially save Model in var

to

var DBappSourceInfoModel = (AppSourceInfo) appSourceInfoModel.Clone();

Upvotes: 0

Views: 3885

Answers (1)

Mark Homer
Mark Homer

Reputation: 1035

You need to perform a Copy (shallow probably sufficient)

var DBappSourceInfoModel = appSourceInfoModel;

Is simply creating a reference to the same object. Implement ICloneable on the DBappSourceInfoModel then use Clone method,

Your Clone method needs to copy all the info to the new Object, also performing Deep Copies on internal references if needed,

This will copy all the details to the other object and create two separate objects,

look here for reference: https://msdn.microsoft.com/en-us/library/system.icloneable%28v=vs.110%29.aspx

EDIT

Just to be clear, you also need to use the IComparable interface to define how the objects are compared for equality,

https://msdn.microsoft.com/en-us/library/system.icomparable%28v=vs.110%29.aspx

Upvotes: 1

Related Questions