Reputation: 2796
Is it possible to add logic to the getter/setter for EntityFramework CodeFirst properties?
For example, I'd like to do something like:
public class Dog {
// This is a normal EF-backed property....
public virtual string Breed { get; set; }
// But we'd like a little logic applied to the Name!
public virtual string Name {
get {
string nameInDB = base.Name;
// where base.Name would be the same as the naked "get;" accessor
if (nameInDB == "Fido") {
return "Fido the Third"
} else {
return nameInDB;
}
}
set;
}
}
public class PetContext : DbContext {
public DbSet<Dog> Dogs;
}
Where the Dog.Name property can be processed a little before returning.
Upvotes: 6
Views: 6123
Reputation: 176
You could use a backing field instead of relying in the auto-implemented property.
private string _Name;
public string Name {
get {
if (_Name == "Fido") {
return "Fido the Third";
} else {
return _Name;
}
}
set {
_Name = value;
{
}
However, I'd go the opposite way, by controlling the value in the setter. To me, this provides more consistency in the model, even on debugging scenarios. You need to consider your actual specs, to see what will suit you better. Example:
private string _Name;
public string Name {
get {
return _Name;
}
set {
if (value == "Fido")
_Name = "Fido the Third";
_Name = value;
{
}
Upvotes: 6