Reputation: 10986
Original
I have an object as a result of Ef 6.0 . I have a single instance of it and want to make sure that ,no other code is able to change its values.
Is there any architecture ,pattern to make sure of it. Immutable,struct,readonly nothing is so clean. or am I asking for too much form such popular language?
Edited
I have an object as a result of Ef 6.0 . I have a single instance of it and want to make sure that ,no other code is able to change its values.
1.Is there any architecture ,pattern to make sure of it. Immutable pattern ,struct,readonly nothing is usable with EF. Am I asking for too much form such popular language?
2.Is there a way to lock an object after required changes are done ?
Upvotes: 0
Views: 1203
Reputation: 1297
this is an old question but I was having the same problem and come up with the following solution, leaving it here so that someone else may benefit in the future:
OriginalData = Context.Entry(MyBindingSource.Current).CurrentValues.ToObject();
Note that MyBindingSource.Current is my entity here.
Upvotes: 0
Reputation: 10986
Answer for making Ef objects immutable :
Private property-setters.
public class Users
{
public int Id { get;private set; }
public string FirstName { get;private set; }
public string LastName { get; private set; }
}
Courtse – J. Steen
Upvotes: 0
Reputation: 587
Think of all the value objects you use. date is a good one. You can take the class' data as part of the constructor and assign those only once at construction. As already pointed out you can make property fields private to set and public to get. For state changing functionality you can return a new instance from the state changing method. A good example is the AddDays method on DateTime. This leaves the original date unchanged but gives you back a new date with the appropriate days added to the original DateTime.
Var date = new DateTime(2015,01,01);
Var newDate = date.AddDays(15);
// date is now 2015,01,01
// newDate is now 2015,01,16
I found this to be the most effective pattern especially as you start needing state changing logic. Great in a multi threaded environment.
Upvotes: 0
Reputation: 156978
Don't have any member that can change the content of your class, like property setters (make the setters private
).
Don't let methods change your variables. (You should make them readonly
probably).
Only mutate fields, properties and variables from the constructor.
Basic example:
public class X
{
public X(string y)
{
this.y = y;
}
private readonly string y;
public string Y { get { return y; } }
}
Upvotes: 6