I\'m playing around with Entity Framework 4.3, and so I am using the DbContext Generator to create the context and entity classes.
With the default EF 4 code genera
I was trying to edit Brian Hinchey solution But EDIT was rejected. Then I post here my addapts to it.
This solution generates Less code for each property Setter, taking advantage of CallerMemberName Attribute.
NOTE: I'm using EF 6.1 and it Works pretty well.
BaseClass now looks as this.
public abstract class BaseModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Update the EntityClassOpening method in the Entity.tt Remains exactly as the Brian's one:
public string EntityClassOpening(EntityType entity)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1}partial class {2}{3}",
Accessibility.ForType(entity),
_code.SpaceAfter(_code.AbstractOption(entity)),
_code.Escape(entity),
_code.StringBefore(" : ", string.IsNullOrEmpty(_typeMapper.GetTypeName(entity.BaseType)) ? "BaseModel" : _typeMapper.GetTypeName(entity.BaseType)));
}
As Bryan say's Remember change :
<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#>
FOR
<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#> : BaseModel
And my last change is for the Property method
public string Property(EdmProperty edmProperty)
{
return string.Format(
CultureInfo.InvariantCulture,
"private {1} {3};\r\n"+
"\t{0} {1} {2} \r\n" +
"\t{{ \r\n" +
"\t\t{4}get {{ return {3}; }} \r\n" +
"\t\t{5}set {{ SetProperty(ref {3}, value); }} \r\n" +
"\t}}\r\n",
Accessibility.ForProperty(edmProperty),
_typeMapper.GetTypeName(edmProperty.TypeUsage),
_code.Escape(edmProperty),
"_" + Char.ToLowerInvariant(_code.Escape(edmProperty)[0]) + _code.Escape(edmProperty).Substring(1),
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}
And Finally here is the class looks like:
public partial class User : BaseModel
{
private int _id;
public int Id
{
get { return _id; }
set { SetProperty(ref _id , value);}
}
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name , value);}
}
}
This makes the generated clases more light.
Recently I was working with PropertyChanged.Fody library but for unknown reasons (at least for me) It doesn't work properly some times. Thats the reason I'm land here. This solution (Bryan's solution) Works every time.